2
\$\begingroup\$

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);
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Feb 5, 2012 at 14:43
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

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);
answered Feb 9, 2012 at 15:10
\$\endgroup\$
1
  • \$\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\$ Commented Apr 13, 2016 at 13:42
5
\$\begingroup\$

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.
answered Feb 16, 2012 at 21:37
\$\endgroup\$
1
  • \$\begingroup\$ The only downside that I could find with this is that it doesn't work properly with multi line strings. \$\endgroup\$ Commented Feb 17, 2012 at 16:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.