How to get the first word of a sentence in PHP?

225,607

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];
Share:
225,607

Related videos on Youtube

ali
Author by

ali

Updated on September 03, 2021

Comments

  • ali
    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?

  • Gordon
    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
    Leo almost 13 years
    NOTE- split() is DEPRECATED from 5.3 >
  • trejder
    trejder about 11 years
    Worth noting, that although strstr is available in PHP since 4.3.0 it was not before 5.3.0, when the optional parameter before_needle (which you're using in this example) was added. Just a notice, because I was confused, why you state, that this example needs 5.3.0.
  • Alberto Fontana
    Alberto Fontana over 9 years
    Briliiant! Better than the original solution
  • zanderwar
    zanderwar almost 9 years
    trim($input) would suffice in this instance :P
  • patrick
    patrick over 8 years
    Note 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
    Admin over 8 years
    Assuming only spaces between words is risky, I'd also include tabs.
  • Elly Post
    Elly Post about 8 years
    Using modern PHP syntax you can just do explode(' ',trim($myvalue))[0]
  • Cédric Françoys
    Cédric Françoys over 7 years
    1 line code for any PHP version : list($firstword) = explode(' ', trim($myvalue), 1);
  • Sdlion
    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
    Admin about 7 years
    What 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
    pbarney over 6 years
    @xxxx, do explode(" ",strip_tags("<media:credit>Dmitry Kostyukov for The New York Times</media:credit>"))[0]
  • Wes
    Wes over 6 years
    This should be the first answer. It only returns the first word like he wanted in a cleaner way.
  • Jay Harris
    Jay Harris over 6 years
    Good 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
    Epoc over 6 years
    I'm using PHP on a daily basis for at least 6 years and I didn't ever heard about this function until now
  • Filnor
    Filnor about 6 years
    @j4k3 Please remember to be nice.
  • j4k3
    j4k3 about 6 years
    If 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
    MarcoZen about 6 years
    RobertPitt -> 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
    Eaten by a Grue almost 6 years
    shouldn't that be echo $i === false ? $myvalue : substr( $myvalue, 0, $i );
  • patrick
    patrick almost 6 years
    This would be the best answer, since it also works for "one, two and three" (the accepted answer would echo "one,")
  • patrick
    patrick almost 6 years
    This is not the best answer! It echoes "one," if the string is "one, two three". The best answer is lower down, @Ciul
  • Arnold Daniels
    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
    Dev Null over 3 years
    Doesn't work. try this with this string: "\n\nNextWord". This answer assumes all words are separate by spaces only.
  • Dev Null
    Dev Null over 3 years
    Doesn't work. try this with this string: "\n\nNextWord". This answer assumes all words are separate by spaces only.
  • Dev Null
    Dev Null over 3 years
    Doesn't work. try this with this string: "\n\nNextWord". This answer assumes all words are separate by spaces only.
  • Dev Null
    Dev Null over 3 years
    Doesn't work. try this with this string: "\n\nNextWord". This answer assumes all words are separate by spaces only.
  • Dev Null
    Dev Null over 3 years
    Doesn't work. try this with this string: "\n\nNextWord". This answer assumes all words are separate by spaces only.
  • Dev Null
    Dev Null over 3 years
    Doesn't work. try this with this string: "\n\nNextWord". This answer assumes all words are separate by spaces only.
  • wheelmaker
    wheelmaker over 3 years
    yes, this does assume a "sentence" is constructed of words separated by spaces
  • Dev Null
    Dev Null about 3 years
    I 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
    Philipp about 3 years
    Words 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,") or Stop! Now (returns "Stop!)
  • mickmackusa
    mickmackusa almost 3 years
    I 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
    mickmackusa almost 3 years
    Why 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
    mickmackusa almost 3 years
    There 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
    mickmackusa almost 3 years
    This 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
    mickmackusa almost 3 years
    This answer does not limit the number of explosions, so it is potentially doing more work than what is required.
  • mickmackusa
    mickmackusa almost 3 years
    There is no reason to wrap \s in a character class.
  • mickmackusa
    mickmackusa almost 3 years
    The $ end of string metacharacter is not necessary for this pattern to work properly.
  • mickmackusa
    mickmackusa almost 3 years
    I would be happier if I saw explode() benchmarks that properly use the limit argument of 2, so that no unnecessary exploding is done.
  • mickmackusa
    mickmackusa almost 3 years
    This late, redundant, unexplained answer missed a great opportunity to limit the number of explosions.
  • mickmackusa
    mickmackusa almost 3 years
    The original question's sample data does not contain any leading newline characters.
  • mickmackusa
    mickmackusa almost 3 years
    Also, if trimming is going to be done, it is logical to only ltrim().