解构弦乐的最快方法

I have a php string of the form :

somename_XXX_someothername_YYY

XXX & YYY = Integers

I want to extract somename and XXX in an array, such that:

array [0] => somename
array [1] => XXX

Following is my approach of achieving it:

$a = array();
$x = 'stack_312_overflow_213';
$a[] = strstr($x, '_', true);
$a[] = strstr(ltrim(strstr($x, '_', false), '_'), '_', true);

I wanted to know if there way any other faster way of doing it as my application will be trimming about 10,000+ strings in this way.

P.S.: I don't know much about speeds, or which php functions are the fastest, so thought of posting it here.

Just use $arr = explode('_', $str); and the values in the [0] and [1] spot are the first two values you requested

Faster then explode and preg_match:

list($word, $num) = sscanf($x, '%[^_]_%d');

Also you will have $num as integer already.

If you are willing to use explode, limit it with 3 to speed it up, also you will lose time on casting int on $num if you need it:

explode('_', $x, 3);

Below are two ways you can get the information from the string. Which one of the two is faster? I really have no idea, but you can test it.

This result is from the explode:

$result = explode('_', 'somename_XXX_someothername_YYY', 3);

print_r($result);

Using a regular expression:

$matches = array();
preg_match('/^(.*?)_(.*?)_/', 'somename_XXX_someothername_YYY', $matches);
array_shift($matches); //will remove the first match, which is "somename_XXX_"

print_r($matches);