Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorten/truncate UTF8 string in PHP

I need a good fast function that shortens strings to a set length with UTF8 support. Adding trailing '...' at ends is a plus. Can anyone help?

like image 620
Alex Avatar asked Dec 13 '22 13:12

Alex


1 Answers

Assuming mb_* functions installed.

function truncate($str, $length, $append = '…') {
  $strLength = mb_strlen($str);

  if ($strLength <= $length) {
     return $str;
  }

  return mb_substr($str, 0, $length) . $append;
}

CodePad.

Keep in mind this will add one character (the elipsis). If you want the $append included in the length that is truncated, just minus the mb_strlen($append) from the length of the string you chop.

Obviously, this will also chop in the middle of words.

Update

Here is a version that can optionally preserve whole words...

function truncate($str, $length, $breakWords = TRUE, $append = '…') {
  $strLength = mb_strlen($str);

  if ($strLength <= $length) {
     return $str;
  }
  
  if ( ! $breakWords) {
       while ($length < $strLength AND preg_match('/^\pL$/', mb_substr($str, $length, 1))) {
           $length++;
       }
  }

  return mb_substr($str, 0, $length) . $append;
}

CodePad.

It will preserve all letter characters up to the first non letter character if the third argument is TRUE.

like image 198
alex Avatar answered Jan 01 '23 14:01

alex