Dipak
Dipak

Reputation: 939

php strtok alternative to split strings

strtok has been recommended and preferred over other function such as explode when string have to split as it returns only one piece at a time, with each subsequent call returning the next piece.

But here, is it better to replace strtok (first-way) with second way? I keep priority to second one, because it is less coded, but don't know about performance and memory consumption in large string. Which one is best ?

$stdt='4-50';    

First way using strtok

$stdt_cut = strtok( $stdt, '-' );
$stdt_final = strtok( '' );
echo $stdt_final;
//output is 50

Second way using substr and strstr

echo substr(strstr($stdt, '-'), 1)
//output is 50

Upvotes: 1

Views: 633

Answers (1)

Elementary
Elementary

Reputation: 1453

The prototype of strstr is:

string strstr ( string $haystack , mixed $needle [, bool $before_needle = FALSE ] )

and the function

Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack.

so based on this:$stdt='4-50';
at this step:strstr($stdt, '-');

you already have '-50'; so you can effectively use:

substr(strstr($stdt, '-'), 1);

or

ltrim(strstr($stdt, '-'),'-');

But a really fast way in you case could be as strpos is stated to be less consuming and more faster than strstr and also because you use all the same substr:

substr($stdt,strpos($stdt,'-')+1)

Upvotes: 2

Related Questions