Any suggestions on better way to remove the last word from a string?

$words = str_word_count($text, 1);
$lastWord = array_pop($words);
$textWithoutLastWord = implode(" ", $words);


$lastSpacePosition = strrpos($text," ");
$textWithoutLastWord =substr($text,0,$lastSpacePosition);

2 Answers 2


Regular expressions are your friend, this should find the last word and remove it while keeping the final punctuation. This may not work with multiline strings, you'll have to fiddle with the regular expression.

$textWithoutLastWord = preg_replace('/\W\w+\s*(\W*)$/', '$1', $words);
  • \$\begingroup\$ Regular expressions are a powerful and complex tool, that should be used when nothing else will do the job. This site is CodeReview. Imagine you're reviewing this code. Is it correct? Is what it does it obvious? Are there any hidden 'gotchas' or edge cases? Who can tell? \$\endgroup\$
    – Guy Gordon
    Commented Apr 13, 2016 at 13:42

My personal preference would be the second option:

$lastSpacePosition = strrpos($text, ' ');
$textWithoutLastWord = substr($text, 0, $lastSpacePosition);
  1. It's more obvious what's happening. The fact that str_word_count returns an array because you feed it a 1, is not obvious.
  2. The code is shorter, in this case I feel that makes it easier to read, rather than obfuscated.
  3. It is by far the fastest. In my text of 110 words copied from a wikipedia article, with 1e6 iterations
    1. str_word_count version took 17.952 milliseconds.
    2. strrpos took 0.597 milliseconds.
    3. preg_replace (By Oscar M) took 71.189 milliseconds.
  4. In my test text the are letters outside of a-z. The str_word_count solution breaks these letters as if spaces. Whether this is, or is not, the intended behaviour of the function, I would stay away from such behaviour.
  • \$\begingroup\$ The only downside that I could find with this is that it doesn't work properly with multi line strings. \$\endgroup\$
    – thedev
    Commented Feb 17, 2012 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.