PHP: Get Substring Before Space (Or Any Other Character)
There are few different ways we can return the portion of a string before the first occurrence of a character in PHP. We will explore some of the best methods in this tutorial so you can determine which one best fits your specific scenario.
The PHP strtok() Function
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.
$string = 'This is a sentence of text.';
$output = strtok($string, ' ');
print($output);
This
The PHP strstr() Function
Another clean way of achieving the same result is to use the PHP strstr()
function. The default behaviour of this function is to return the substring of a string after the first match of a character. If true
is supplied as the third argument the substring before a character will be returned.
$string = 'This is a sentence of text.';
$output = strstr($string, ' ', true);
print($output);
This
The PHP substr() Function
The PHP substr()
function is another way to get the substring before a space. It is slightly less favourable since it has to be used with the strpos()
function to find the first occurrence of a particular character in the string.
$string = 'This is a sentence of text.';
$output = substr($string, 0, strpos($string, ' '));
print($output);
This
PHP explode() + list() Functions
Yet another methods is to use the PHP explode()
and list()
functions. This method is likely to only be preferable if all the solutions above don't work for you.
$string = 'This is a sentence of text.';
$output = list($firstWord) = explode(' ', $string);
print($output[0]);
This