1

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 or letters, but limit the letters and cut it off at the nearest word.

Say I had two strings:

"This is a block of text, blah blah blah"
"this is another block of txt 2 work with"

Say I wanted to limit it to 27 characters, the first line would end at "blah" and the second on would end at "txt" even though the character limits are reached within those words.

Is there any clean solution to this problem?

Sam Becker
  • 19,231
  • 14
  • 60
  • 80

6 Answers6

2

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")

J.C. Inacio
  • 4,442
  • 2
  • 22
  • 25
1

I wrote a max-string-length function that does just this and is very clean.

aleemb
  • 31,265
  • 19
  • 98
  • 114
0
// 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]. '...';
}
amateur barista
  • 4,440
  • 3
  • 25
  • 37
0

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?

Andrei Serdeliuc ॐ
  • 5,828
  • 5
  • 39
  • 66
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;
    }
}
Kieran Hall
  • 2,637
  • 2
  • 24
  • 27
0

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'
Ciaran McNulty
  • 18,698
  • 6
  • 32
  • 40