A recent PHP Web site project News section needs a feature to intercept the string according to the width of the title and add "..." at the end, the first thought is the use of PHP mb_ string function Implementation, Mb_strimwidth,mb_strwidth, after the discovery if the title exists "" Symbol, PHP Mb_strwidth will think of the symbol is 1 width, I wonder if this is not Chinese double quotation marks, it is supposed to be wide-byte, length should be 2 width, after query "" Unicode respectively is u201c and u201d, not in the range of characters, Then query the unicode.org Code table, found that u2000-u206f is a universal symbol of the range, the characters in this range, although all the form of wide characters, but PHP mb_ function is considered to be 1 width, no way, only on their own.
The following are the implemented functions:
- function truncstring ($STR, $length)
- {
- $ Countlen = 0 ;
- for ($i=0; $i<Mb_strlen($STR); $ i++)
- {
- $countLen +=amb_strwidth (Mb_substr ($str, $i, 1));
- if ($countLen>$length)
- Return Mb_substr ($str, 0, $i);
- }
- return $str;
- }
- function Amb_strwidth ($str _width)
- {
- $ Count = 0 ;
- for ($i=0; $i<Mb_strlen($ Str_width), $i + +)
- {
- if (Mb_substr ($str _width, $i, 1) = = "Xe2x80x9c" | | Mb_substr ($str _width, $i, 1) = = ' xe2x80x9d ')
- Add 2 to the counter if you encounter characters in u2000-u206f
- if (Preg_match ("/[x{2000}-x{206f}]/u", Mb_substr ($str _width, $i, 1)))
- $count +=2;
- Else
- $count +=mb_strwidth (Mb_substr ($str _width, $i, 1));
- }
- return $count;
- }
The above is the use of PHP mb_strwidth when the problem of the specific solution, I hope to play a role in helping people.
http://www.bkjia.com/PHPjc/446292.html www.bkjia.com true http://www.bkjia.com/PHPjc/446292.html techarticle A recent PHP website Project news section needs a feature to intercept the string by the width of the title and add it at the end ..., the first thought is to use PHP mb_ string function Implementation ...