Page 1 of 1

First x words only?

Posted: Wed Sep 17, 2003 2:03 pm
by Unipus
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.

Posted: Wed Sep 17, 2003 3:53 pm
by Unipus
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; 
	}

Posted: Wed Sep 17, 2003 4:05 pm
by Unipus
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; 
	}

Posted: Wed Sep 17, 2003 7:00 pm
by pootergeist
or

Code: Select all

$maxlen = 150;
$str = (strlen($str) <= $maxlen) ? $str : substr($str,0,strrpos(substr($str,0,$maxlen),' '));
as a function maybe

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, '...');
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

Posted: Wed Sep 17, 2003 7:29 pm
by Unipus
Yeah, I know about the MySQL functions, but couldn't use them in this particular instance without making an even bigger hassle.