If I've got a variable length string being returned from a database, how can I quickly (no regex if possible!) reduce that string to only the first x words?
In pseudo code:
$TextString = whateverthisfunctionmightbe($TextString,8);
would return "There is a tide in the affairs of" for the given TextString "There is a tide in the affairs of men, which, taken at the flood..."
What I want is exactly like substr, but for words instead of characters. Actually, the issue here is that I am dealing with a small area in which to display between 10 and 150 character results, and don't want to chop off words in the middle. What would be great is if this function could accomodate extreme differences in word length... sort of a combination of substr and the function described above.
First x words only?
Moderator: General Moderators
Thanks. Tweaked a bit:
Code: Select all
function show_x_words ($string,$number) {
$split = explode(" ",$string);
for ($x=0;$x<$number;$x++) {
if ($x != $number)
$text .= "{$split[$x]} ";
else
$text .= $split[$x];
}
return $text;
}Actually, further tweaked to indicate when the string has actually been chopped off.
Code: Select all
function show_x_words ($string,$number) {
$split = explode(" ",$string);
for ($x=0;$x<$number;$x++) {
if ($x != $number)
$text .= "{$split[$x]} ";
else
$text .= $split[$x];
}
if (count($split) > $number)
$text .= "...";
return $text;
}-
pootergeist
- Forum Contributor
- Posts: 273
- Joined: Thu Feb 27, 2003 7:22 am
- Location: UK
or
as a function maybe
You should also note that mysql has built in truncation functions for use in queries - search out substring and substring_index in the mysql manual - substring_index is extremely useful in that it can return a set number of words by using space as the delimiter
Code: Select all
$maxlen = 150;
$str = (strlen($str) <= $maxlen) ? $str : substr($str,0,strrpos(substr($str,0,$maxlen),' '));Code: Select all
function truncate($full_str_ref, $trunc_pos, $trunc_ext = '[...]')
{
return (strlen($full_str_ref) < $trunc_pos) ?
$full_str_ref :
substr($full_str_ref, 0, strrpos(substr($full_str_ref.' ',0,$trunc_pos+1),' ')).$trunc_ext;
}
$string = 'very long string here with a few spaces';
echo truncate($string, 9, '...');