2

I have a string that contains some values I need to extract. Each of these values is surrounded by a common character.

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

2
  • 1
    Most efficient in terms of memory or CPU time? Most efficient in PHP?.. Commented Sep 8, 2011 at 10:55
  • 1
    Why did this question get a negative vote? Commented Sep 8, 2011 at 11:02

6 Answers 6

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

preg_match_all

Sign up to request clarification or add additional context in comments.

Comments

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

5 Comments

incorrect: array(4) { [0]=> string(15) "stackoverflowis" [1]=> string(6) "value1" [2]=> string(13) "butyouarevery" [3]=> string(6) "value2" }
@k102 it is much more efficient to read each even item from array, then to hope that there will be % at the end of string , and not at the start.
@tereško i don't agree. how can you tell that $array[1] is one of needed strings and $array[0] not? all i want to say - your answer is not full
@k102 do you not see that your own code has the same problem ? what if string is "stackoverflowis%value1%butyouarevery%value2" ? or "%stackoverflowis%value1%butyouarevery%value2%" ?
@tereško my code works on given string. yours - is only a part of a code.
1
$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" }

Comments

1

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>';

1 Comment

explode wouldn't extract values, it'll just split string into array
1

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 />';
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.