在PHP中拆分字符串的最快捷,最有效的方法

I need to split string by just finding the first character. What is the quickest way to write it?

An example of string:

$string = 'Some text here| some text there--and here|another text here';

Expected result:

$new_string = 'Some text here';

This is a solution, I have. Is there a more efficient way to do it?

$explode = explode('|', $string);  
$new_string = explode[0];

Use strpos() and substr(). Strpos() will return as soon as the first occurrence is found, while explode() has to walk the whole string.

best would be go with:

$first = strtok($string, '|');

you can go and with explode if you like it:

$explode = explode('|', $string, 1);

also strpos(), substr() and strstr() is good for this.

Use strstr():

strstr($string, "|", true);

Will return everything until the first pipe (|).

$string = 'Some text here| some text there--and here|another text here';
$string = substr($string, 0, strpos($string,'|'));
print $string;

Edit: Using strstr() is better.

explode can be turned into one-liner with

list($first,) = explode('|', $string,2);

however, strtok looks like most concise solution.

As for the efficiency - it doesn't matter at all, which way to choose to perform such a negligible operation.

Whatever inefficiency is coming from the amount of processed data. And sane programmer would avoid processing large amounts of data at any cost. While whatever else matters are complete rubbish from the efficiency point of view.