简体   繁体   中英

Cut strings (UTF-8) (PHP)

How to cut string in UTF 8.

I have searched from web this function:

function cutString($str, $lenght = 100, $end = ' …', $charset = 'UTF-8', $token = '~') {
    $str = strip_tags($str);
    if (mb_strlen($str, $charset) >= $lenght) {
        $wrap = wordwrap($str, $lenght, $token);
        $str_cut = mb_substr($wrap, 0, mb_strpos($wrap, $token, 0, $charset), $charset);   
        return $str_cut .= $end;
    } else {
        return $str;
    }
}

But result of this function isn't too good. Because if we set to cut 200 letters, it will return about 110, but I need about 200.

I have just tested it and it works fine. If you run it with

echo cutString($mystring, 200);

It returns 201 characters from the string I gave it.

i think wordwrap() function does wrong in this case cut the string manually. i use a function like this (just add 'mb_' and $charset to the string functions):

function str_cut_end_by_word($s, $max_len, $trailer = "...")
{
  if (strlen($s) <= $max_len)
    return $s;

  $s = trim($s);
  $s = substr($s, 0, $max_len);

  for ($i = strlen($s) - 1; $i >= 0; $i--)
  {
    if (in_array($s{$i}, array(" ", "\t", "\r", "\n")))
    {
      return rtrim(substr($s, 0, $i)).$trailer;
    }
  }

  return $s;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM