Here is the question: How would your trim a block of text to the nearest word when a certain amount of characters have past. I\'m not trying to limit a certain number words
See the wordwrap function.
I would probably do something like:
function wrap($string) {
$wstring = explode("\n", wordwrap($string, 27, "\n") );
return $wstring[0];
}
(If your strings already span across severeal lines, use other char - or pattern - for the split other than "\n")
You can use a little-known modifier to str_word_count to help do this. If you pass the parameter '2', it returns an array of where the word position are.
The following is a simple way of using this, but it might be possible to do it more efficiently:
$str = 'This is a string with a few words in';
$limit = 20;
$ending = $limit;
$words = str_word_count($str, 2);
foreach($words as $pos=>$word) {
if($pos+strlen($word)<$limit) {
$ending=$pos+strlen($word);
}
else{
break;
}
}
echo substr($str, 0, $ending);
// outputs 'this is a string'
// Trim very long text to 120 characters. Add an ellipsis if the text is trimmed.
if(strlen($very_long_text) > 120) {
$matches = array();
preg_match("/^(.{1,120})[\s]/i", $very_long_text, $matches);
$trimmed_text = $matches[0]. '...';
}
I think this should do the trick:
function trimToWord($string, $length, $delimiter = '...')
{
$string = str_replace("\n","",$string);
$string = str_replace("\r","",$string);
$string = strip_tags($string);
$currentLength = strlen($string);
if($currentLength > $length)
{
preg_match('/(.{' . $length . '}.*?)\b/', $string, $matches);
return rtrim($matches[1]) . $delimiter;
}
else
{
return $string;
}
}
I wrote a max-string-length function that does just this and is very clean.
Wouldn't it be simpler to concat the strings using a place holder (i.e.: ###PLACEHOLDER###), count the chars of the string minus your place holder, trim it to the right length with substr and then explode by placeholder?