Truncate a string in PHP without breaking words

I was working on PHP project that require to get a text from MySQL and display only 50 character. Thus I used php substr function to truncate a text to first 50 character.

$text="quick brown fox jumps over the lazy dog. quick brown fox jumps over the lazy dog.";
echo substr($text, 0, 50);

Output Of above code
quick brown fox jumps over the lazy dog. quick bro

As we can see this code works but its breaking last word. So I search the web and found many solution on stackoverflow to truncate a string without word break.

First solution

$text="quick brown fox jumps over the lazy dog. quick brown fox jumps over the lazy dog.";
function Truncate($string, $length) {
  $parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);
  $parts_count = count($parts);
 
  $length = 0;
  $last_part = 0;
  for (; $last_part < $parts_count; ++$last_part) {
    $length += strlen($parts[$last_part]);
    if ($length > $length) { break; }
  }
 
  return implode(array_slice($parts, 0, $last_part));
}
echo Truncate($text,50);

Output of above code

quick brown fox jumps over the lazy dog. quick

As we can see above code works without word break. It returns first 50 characters, if 50th character is between word then its truncate whole word. This code works as expected but I found another shorter solution on stackoverflow

Second solution (recommended)

$text="quick brown fox jumps over the lazy dog. quick brown fox jumps over the lazy dog.";
function Truncate($text,$length)
{
 if (preg_match('/^.{1,'.$lenght.'}\b/su', $text, $match))
   {
    return $match[0];
   }
else
    return $text;
}

echo Truncate($text,50);

Output

quick brown fox jumps over the lazy dog. quick

Output of second code is same a first one. But second code is much shorter then first code. It is just using regular expression to match first 50 characters with word boundary. If length of given text is shorter then desired length then it returns whole text.

If you have any better solution to truncate a string without breaking words. Then share it in comments.

Published by Sunny

A Mechanical engineer by education and web developer by passion and profession. He lives in Lucknow, India. Currently earning his livings by hitting keyboad. ;)

Leave a comment

Your email address will not be published. Required fields are marked *