Forum Moderators: coopster
/**
* Returns the last N words from the passed string
* @param string $text The original text to analyse
* @param int $numWords (OPTIONAL) The number of words to return, default 1
* @return string
*/
function getLastWordsStr($text,$numWords=1) {
$nonWordChars = ':;,.?![](){}*';
$result = '';
$words = explode(' ',$text);
$wordCount = count($words);
if ($numWords > $wordCount) {
$numWords = $wordCount;
}
for ($w = $numWords; $w > 0; $w--) {
if (!empty($result)) {$result .= ' ';}
$result .= trim($words[$wordCount - $w], $nonWordChars);
}
return $result;
}
$words = preg_split('\W+', $text, 0, PREG_SPLIT_NO_EMPTY);
$words = preg_split('\W+', $text, 0, PREG_SPLIT_NO_EMPTY); '/[^\'\w]+/' and then avoid the trim?