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?
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?
Even though it is little late, but PHP has one better solution for this:
Regards, Ciul
If you have PHP 5.3
note that if
$myvalue
is a string with one wordstrstr
doesn't return anything in this case. A solution could be to append a space to the test-string: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:
Or using explode, which has so many answers using it I won't bother pointing out how to do it.
You could do
You can use the explode function as follows: