Home > Backend Development > PHP Tutorial > Detailed Chinese interception function mb_substr() in php_PHP tutorial

Detailed Chinese interception function mb_substr() in php_PHP tutorial

WBOY
Release: 2016-07-13 10:55:23
Original
1110 people have browsed it

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:

$str, the string to calculate the length
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 )
$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. ...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template