1

我有以下函数用“...”替换超过 32 个字符的字符串。我的问题是,如果变音符号落在第 29 到第 33 个字符的范围内,它会由一个奇怪的字符表示。如何更改函数以显示整个变音符号而不破坏它,尽管我在变量 $length 中放置了多少数字长度?

例如,für 前面有 31 个字符,但使用下面的函数,它会给出 31 个字符加上 f...

function textLimit($string, $length, $replacer = '...')
{
  if(strlen($string) > $length)
  return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;

  return $string;
}
4

1 回答 1

1

您似乎正在使用 UTF-8 字符串和两者strlensubstr而您preg_match并没有意识到这一点。对于字符串函数,您需要使用 this:

http://www.php.net/manual/en/ref.mbstring.php

以下示例应使用 UTF-8 字符串(注意 mb 函数和 u preg 修饰符):

function textLimit($string, $length, $replacer = '...') {
  if(mb_strlen($string) > $length) {
    return (preg_match('/^(.*)\W.*$/u', mb_substr($string, 0, $length+1), $matches) ? $matches[1] : mb_substr($string, 0, $length)) . $replacer;
  }

  return $string;
}

mb_internal_encoding('UTF-8');
echo 'example: '.textLimit('füüür', 2)."\n";

输出:

example: fü...
于 2012-11-21T12:55:04.400 回答