开发者

PHP - Most efficient way to extract substrings based on given delimiter?

I have a string that contains some values I need to extract. Each of these values is surrounded by a common cha开发者_运维问答racter.

What is the most efficient way to extract all of these values into an array?

For example, given the following string:

stackoverflowis%value1%butyouarevery%value2%

I would like to get an array containing value1 and value2


$s = "stackoverflowis%value1%butyouarevery%value2%";
preg_match_all('~%(.+?)%~', $s, $m);
$values = $m[1];

preg_match_all


$string = 'stackoverflowis%value1%butyouarevery%value2%';
$string = trim( $string, '%' ); 
$array = explode( '%' , $string );


$str = "stackoverflowis%value1%butyouarevery%value2%";
preg_match_all('/%([a-z0-9]+)%/',$str,$m);
var_dump($m[1]);

array(2) { [0]=> string(6) "value1" [1]=> string(6) "value2" }


Give a try to explode. Like $array = explode('%', $string);

LE:

<?php

$s = 'stackoverflowis%value1%butyouarevery%value2%';
$a = explode('%', $s);
$a = array_filter($a, 'strlen'); // removing NULL values
$last = ''; // last value inserted;
for($i=0;$i<=count($a);$i++)
    if (isset($a[$i+1]) && $a[$i] <> $last)
        $t[] = $last = $a[$i+1];

echo '<pre>'; print_r($t); echo '</pre>';


Use explode and take the odd-indexed values from the resulting array. You indicated you wanted the most efficient method, and this will be faster than a regex solution.

$str = 'stackoverflowis%value1%butyouarevery%value2%';
$arr = explode('%', $str);

$ct = count($arr);

for ($i = 1; $i < $ct; $i += 2) {
    echo $arr[$i] . '<br />';
}


preg_match_all('/%([^%]+)%/', $s, $match);
var_dump($match[1]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜