Since Chinese characters are two bytes, you cannot use substr() like English and numbers. This will cause garbled characters. Fortunately, there is the mb_substr() function in PHP to handle this problem. Friends in need can take a look.
1. Chinese interception: mb_substr()
mb_substr( $str, $start, $length, $encoding )
$str, the string that needs to be truncated
$start, the beginning of truncation, the starting point is 0
$length, the number of words to be intercepted
$encoding, web page encoding, such as utf-8, GB2312, GBK
Example:
The code is as follows
代码如下 |
复制代码 |
$str='电影618:http://www.bKjia.c0m';
echo mb_substr($str,0,5,'utf-8');//截取头5个字,假定此代码所在php文件的编码为utf-8
?>
|
|
Copy code
|
$str='Movie 618: http://www.bKjia.c0m';
echo mb_substr($str,0,5,'utf-8');//Intercept the first 5 words, assuming that the encoding of the php file where this code is located is utf-8
?>
The results show: Movie 618
代码如下 |
复制代码 |
$str='电影618:http://www.hzhuti.com';
echo mb_strlen($str,'utf-8');//假定此代码所在php文件的编码为utf-8
?>
|
2. Get the Chinese length: mb_strlen()
mb_strlen( $str, $encoding ) |
$str, the string to calculate the length
$encoding, web page encoding, such as utf-8, GB2312, GBK
Example:
The code is as follows
|
Copy code
$str='Movie 618: http://www.hzhuti.com';
echo mb_strlen($str,'utf-8');//Assume that the encoding of the php file where this code is located is utf-8
?>
The result shows: 29
http://www.bkjia.com/PHPjc/632257.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632257.htmlTechArticleBecause Chinese is two bytes, you cannot use substr() like English and numbers. This will cause garbled characters. Fortunately, there is the mb_substr() function in PHP to handle this problem. Friends in need can take a look. ...
|
|