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);
Remove last word from string
php;strings
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);