Entry
How do I get the first n words of a string?
How do I get the last n words of a string?
May 29th, 2002 09:43
Philip Olson, Jacob Stetser,
One way is to create an array from all the words of the string by
splitting the string. For example, let's split on spaces:
$str = "hello, today sure is a nice day";
$words = split('[ ]+', $str);
print $words[0]; // hello
print $words[2]; // sure
To use only a portion of this array of words, consider the
array_slice() function:
$somewords = array_slice($words, 0, 20);
Now we have an array of the first 20 words. Let's put it all together
now:
function get_some_words($str, $count = 20)
{
$words = split('[ ]+', $str);
if (sizeof($words) > $count) {
$words = array_slice($words, 0, $count);
}
return implode($words, ' ');
}
Note that what you split on is important. In our example above we
treat multiple spaces ' ' the same as single spaces ' '. Let's say
you want to eliminate all non alpha-numerical characters during the
split, then use this regex instead:
$words = split('[^[:alnum:]]+', $str);
In our example function, all multiple spacings will result in single
spacing after going through get_some_words(). So ' ' => ' '.
See also: http://www.php.net/split
http://www.php.net/preg_split