In PHP, what is the simplest way to return the portion of a string before the first occurrence of a specific character?
For example, if I have a string...
\"
How about this:
$string = "The quick brown fox jumped over the etc etc.";
$splitter = " ";
$pieces = explode($splitter, $string);
echo $pieces[0];
strstr() Find the first occurrence of a string. Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack.
Third param: If TRUE, strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle).
$haystack = 'The quick brown foxed jumped over the etc etc.';
$needle = ' ';
echo strstr($haystack, $needle, true);
Prints The
.
for googlers: strtok is better for that
echo strtok("The quick brown fox", ' ');
You could do this:
$string = 'The quick brown fox jumped over the lazy dog';
$substring = substr($string, 0, strpos($string, ' '));
But I like this better:
list($firstWord) = explode(' ', $string);
To sum up there're 4 ways
strstr($str,' ',true);
strtok($str,' ');
explode(' ', $str)[0]; //slowest
substr($str, 0, strpos($str, ' '));
The difference is that if no delimiter found:
strstr
returns false
strtok
explode
returns whole string
substr
returns empty string
if unexpected troubles with multibyte appear then this example
$str = mb_strstr($str, 'и', true) ?: $str;