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".
The easiest way to get a substring before the first occurrence of a character such as a whitespace is to use the PHP strtok() function. Pass the string to check as the first argument and the character to look for as the second.
The substr() function returns a part of a string.
The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.
The substr() function used to cut a part of a string from a string, starting at a specified position. The input string. Refers to the position of the string to start cutting. A positive number : Start at the specified position in the string.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With