Get first 100 characters from string, respecting full words

Solution 1:

All you need to do is use:

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

Solution 2:

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.

Solution 3:

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.

Solution 4:

This is my approach, based on amir's answer, but it doesn't let any word make the string longer than the limit, by using strrpos() with a negative offset.

Simple but works. I'm using the same syntax as in Laravel's str_limit() helper function, in case you want to use it on a non-Laravel project.

function str_limit($value, $limit = 100, $end = '...')
{
    $limit = $limit - mb_strlen($end); // Take into account $end string into the limit
    $valuelen = mb_strlen($value);
    return $limit < $valuelen ? mb_substr($value, 0, mb_strrpos($value, ' ', $limit - $valuelen)) . $end : $value;
}

Solution 5:

Sure. The easiest is probably to write a wrapper around preg_match:

function limitString($string, $limit = 100) {
    // Return early if the string is already shorter than the limit
    if(strlen($string) < $limit) {return $string;}

    $regex = "/(.{1,$limit})\b/";
    preg_match($regex, $string, $matches);
    return $matches[1];
}

EDIT : Updated to not ALWAYS include a space as the last character in the string