Get first 100 characters from string, respecting full words

05/04/2020 05:00:02

I have asked a similar question here before, but I need to know if this little tweak is possible. I want to shorten a string to 100 characters and use $small = substr($big, 0, 100); to do so. However, this just takes the first 100 characters and doesn't care whether it breaks up a word or not.

Is there any way to take up to the first 100 characters of a string but make sure you don't break a word?

Example:

$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"

$small = some_function($big);

echo $small;

// OUTPUT: "This is a sentence that has more than 100 characters in it, and I want to return a string of only"

Is there a way to do this using PHP?

Verified Answer (134 Votes)

01/05/2011 11:37:00

All you need to do is use:

$pos=strpos($content, ' ', 200);
substr($content,0,$pos ); 
134

Answer #2 (37 Votes)

06/10/2009 01:25:31

Yes, there is. This is a function I borrowed from a user on a different forums a a few years back, so I can't take credit for it.

//truncate a string only at a whitespace (by nogdog)
function truncate($text, $length) {
   $length = abs((int)$length);
   if(strlen($text) > $length) {
      $text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
   }
   return($text);
}

Note that it automatically adds ellipses, if you don't want that just use '\\1' as the second parameter for the preg_replace call.

37

Answer #3 (20 Votes)

06/10/2009 01:26:25

If you define words as "sequences of characters delimited by space"... Use strrpos() to find the last space in the string, shorten to that position, trim the result.

20
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.