Return the portion of a string before the first occurrence of a character in PHP
PhpStringPhp Problem Overview
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...
"The quick brown foxed jumped over the etc etc."
...and I am filtering for a space character (" "), the function would return "The".
Php Solutions
Solution 1 - Php
For googlers: strtok is better for that:
echo strtok("The quick brown fox", ' ');
Solution 2 - Php
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);
Solution 3 - Php
> 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
.
Solution 4 - Php
Use this:
$string = "The quick brown fox jumped over the etc etc.";
$splitter = " ";
$pieces = explode($splitter, $string);
echo $pieces[0];
Solution 5 - Php
To sum up, there're four ways. Delimiter =
:
strstr($str, '=', true);
strtok($str, '=');
explode('=', $str)[0]; // Slowest
substr($str, 0, strpos($str, '='));
This table illustrates output differences. Other outputs are pretty isomorphic.
+-------+----------------+----------+-------+----------------+-------+-------+
| $str | "before=after" | "=after" | "=" | "no delimeter" | 1 | "" |
+-------+----------------+----------+-------+----------------+-------+-------+
| 1. | "before" | "" | "" | false | false | false |
| 2. | "before" | "after" | false | "no delimeter" | "1" | false |
| 3. | "before" | "" | "" | "no delimeter" | "1" | "" |
| 4. | "before" | "" | "" | "" | "" | "" |
If troubles with multibyte appear then try for example mb_strstr
:
mb_strstr($str, 'ζ', true);
Further notice: explode
seems to be more straightforward, deals with multibyte and by passing third parameter returns both before and after delimeter
explode('ζ', $str, 2);
Solution 6 - Php
The strtok() function splits a string into smaller strings, for example:
$string = "The quick brown";
$token = strtok($string, " "); // Output: The
And if you don’t have spaces: print all characters
$string = "Thequickbrown";
$token = strtok($string, " "); // Output: Thequickbrown