How to get the first word of a sentence in PHP?
I want to extract the first word of a variable from a string. For example, take this input:
<?php $myvalue = 'Test me more'; ?>
The resultant output should be Test
, which is the first word of the input.
How can I do this?
There is a string function (strtok) which can be used to split a string into smaller strings (tokens) based on some separator(s). For the purposes of this thread, the first word (defined as anything before the first space character) of Test me more
can be obtained by tokenizing the string on the space character.
<?php
$value = "Test me more";
echo strtok($value, " "); // Test
?>
For more details and examples, see the strtok PHP manual page.
You can use the explode function as follows:
$myvalue = 'Test me more';
$arr = explode(' ',trim($myvalue));
echo $arr[0]; // will print Test
Another example:
$sentence = 'Hello World this is PHP';
$abbreviation = explode(' ', trim($sentence ))[0];
echo $abbreviation // will print Hello
If you have PHP 5.3
$myvalue = 'Test me more';
echo strstr($myvalue, ' ', true);
note that if $myvalue
is a string with one word strstr
doesn't return anything in this case. A solution could be to append a space to the test-string:
echo strstr( $myvalue . ' ', ' ', true );
That will always return the first word of the string, even if the string has just one word in it
The alternative is something like:
$i = strpos($myvalue, ' ');
echo $i !== false ? $myvalue : substr( $myvalue, 0, $i );
Or using explode, which has so many answers using it I won't bother pointing out how to do it.
You could do
echo current(explode(' ',$myvalue));