How to get the first word of a sentence in PHP?
Solution 1
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
Solution 2
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.
Solution 3
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.
Solution 4
You could do
echo current(explode(' ',$myvalue));
Solution 5
Even though it is little late, but PHP has one better solution for this:
$words=str_word_count($myvalue, 1);
echo $words[0];
Related videos on Youtube
ali
Updated on September 03, 2021Comments
-
ali over 2 years
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?-
caw almost 8 yearsYou might find
s($str)->words()[0]
helpful, as found in this standalone library. -
mickmackusa almost 3 yearsA small table of potential fringe cases when getting the substring before the first occurrence of a character: stackoverflow.com/a/68123370/2943403
-
-
Gordon about 14 years+1 for not using explode or regex (both inappropriate imho). Another alternative would be to use strstr with str_replace, replacing the part after the needle from strstr with nothing.
-
Leo almost 13 yearsNOTE- split() is DEPRECATED from 5.3 >
-
trejder about 11 yearsWorth noting, that although
strstr
is available in PHP since4.3.0
it was not before5.3.0
, when the optional parameterbefore_needle
(which you're using in this example) was added. Just a notice, because I was confused, why you state, that this example needs5.3.0
. -
Alberto Fontana over 9 yearsBriliiant! Better than the original solution
-
zanderwar almost 9 years
trim($input)
would suffice in this instance :P -
patrick over 8 yearsNote that if you set myvalue to a single word strstr doesn't return anything in this case! A solution could be to always add a space at the end of the string that's tested so it always comes back with the first word, even if that's the only word in the string!
-
Admin over 8 yearsAssuming only spaces between words is risky, I'd also include tabs.
-
Elly Post about 8 yearsUsing modern PHP syntax you can just do
explode(' ',trim($myvalue))[0]
-
Cédric Françoys over 7 years1 line code for any PHP version :
list($firstword) = explode(' ', trim($myvalue), 1);
-
Sdlion about 7 years@CédricFrançoys the
limit
parameter should be 2 since it has to include the last element that contains the rest of the string; 1 would just return the very same string. Unless a big array would be created I would go with Elliot version for a one liner. -
Admin about 7 yearsWhat if you want the second word as well as from RSS NewYorkTimes - media:credit is - <media:credit>Dmitry Kostyukov for The New York Times</media:credit> . I only want Dmitry Kostyukov - How do I do that? =)
-
pbarney over 6 years@xxxx, do
explode(" ",strip_tags("<media:credit>Dmitry Kostyukov for The New York Times</media:credit>"))[0]
-
Wes over 6 yearsThis should be the first answer. It only returns the first word like he wanted in a cleaner way.
-
Jay Harris over 6 yearsGood solution but in the php manual, it warns: This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.
-
Epoc over 6 yearsI'm using PHP on a daily basis for at least 6 years and I didn't ever heard about this function until now
-
Filnor about 6 years@j4k3 Please remember to be nice.
-
j4k3 about 6 yearsIf you're looking for the most inefficient way to get the first word in a string, this is a good solution. In all other cases you're better off with literally every other answer here. How does this get any upvotes?
-
MarcoZen about 6 yearsRobertPitt -> It would be helpful if you gave an example where strtok failed with a word boundary as compared to a preg_split.
-
Eaten by a Grue almost 6 yearsshouldn't that be
echo $i === false ? $myvalue : substr( $myvalue, 0, $i );
-
patrick almost 6 yearsThis would be the best answer, since it also works for "one, two and three" (the accepted answer would echo "one,")
-
patrick almost 6 yearsThis is not the best answer! It echoes "one," if the string is "one, two three". The best answer is lower down, @Ciul
-
Arnold Daniels over 5 years
strtok
is a weird and dangerous function that holds a global state. Using this function should be discouraged. -
Dev Null over 3 yearsDoesn't work. try this with this string: "\n\nNextWord". This answer assumes all words are separate by spaces only.
-
Dev Null over 3 yearsDoesn't work. try this with this string: "\n\nNextWord". This answer assumes all words are separate by spaces only.
-
Dev Null over 3 yearsDoesn't work. try this with this string: "\n\nNextWord". This answer assumes all words are separate by spaces only.
-
Dev Null over 3 yearsDoesn't work. try this with this string: "\n\nNextWord". This answer assumes all words are separate by spaces only.
-
Dev Null over 3 yearsDoesn't work. try this with this string: "\n\nNextWord". This answer assumes all words are separate by spaces only.
-
Dev Null over 3 yearsDoesn't work. try this with this string: "\n\nNextWord". This answer assumes all words are separate by spaces only.
-
wheelmaker over 3 yearsyes, this does assume a "sentence" is constructed of words separated by spaces
-
Dev Null about 3 yearsI think you missed the point. I upper-cased "W" in word so you could read it easier. Maybe this will make more sense to you - "\n\nThis won't work". The above code will think the first word is "\n\nThis"
-
Philipp about 3 yearsWords do not end at the first space, but at the first character, that's not a letter. For eample
"Hey, how are you?
(returns "Hey,") orStop! Now
(returns "Stop!) -
mickmackusa almost 3 yearsI would not capture the
\s*
. I would not write[^\s]
because\S
is simpler. I would not capture the.*
at the end. This answer is doing too many unnecessary things for a such a small snippet. -
mickmackusa almost 3 yearsWhy use
i
pattern modifier if the character class has[a-zA-Z]
or if you are using\w
? What should the output be if the first "word" contains an apostrophe or hyphen? Food for thought. This unexplained answer is teaching unnecessary things. -
mickmackusa almost 3 yearsThere is no limit to the
split()
, so this technique will be over-functioning. It only needs to explode on the first occurring space to do the job properly. -
mickmackusa almost 3 yearsThis answer seems more like a comment. It seems to be trying to weigh-in on other answers. I don't know how
extract()
is useful here.preg_
functions will be slower, but they offer more robust techniques that can weed out unwanted characters in fringe cases. -
mickmackusa almost 3 yearsThis answer does not limit the number of explosions, so it is potentially doing more work than what is required.
-
mickmackusa almost 3 yearsThere is no reason to wrap
\s
in a character class. -
mickmackusa almost 3 yearsThe
$
end of string metacharacter is not necessary for this pattern to work properly. -
mickmackusa almost 3 yearsI would be happier if I saw
explode()
benchmarks that properly use the limit argument of2
, so that no unnecessary exploding is done. -
mickmackusa almost 3 yearsThis late, redundant, unexplained answer missed a great opportunity to limit the number of explosions.
-
mickmackusa almost 3 yearsThe original question's sample data does not contain any leading newline characters.
-
mickmackusa almost 3 yearsAlso, if trimming is going to be done, it is logical to only
ltrim()
.