Forum Moderators: coopster
<?php
function lastWord($sentence) {
// Break the sentence into its component words:
$words = explode(' ', $sentence);
// Get the last word and trim any punctuation:
$result = trim($words[count($words) - 1], '.?![](){}*');
// Return a result:
return $result;
}
$string = "Lorem ipsum dolor sit amet consectetuer.";
echo lastWord($string);
?>
Returns:
consectetuer
Good reading on string manipulation (plus links to the various regex functions) here [php.net].
-- b
Hard to say. Run a few tests to find out. microtime() is pretty good for something like this, actually. Read the documentation for more information. For something like this, however, it's not likely that there will be much of a difference.
$string = 'Here is a sentence';
$last_word = [url=http://www.php.net/substr]substr[/url]($string, [url=http://www.php.net/strrpos]strrpos[/url]($string, ' '));