Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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);

or

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

Thanks.

share|improve this question

2 Answers

up vote 2 down vote accepted

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);
share|improve this answer

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.
share|improve this answer
The only downside that I could find with this is that it doesn't work properly with multi line strings. – thedev Feb 17 '12 at 16:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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