<pre style="font-family:Consolas; font-size:12pt">方法一:
<?php header("Content-Type: text/html; charset=utf-8");$str="107sadf网站工作室欢迎您!"; echo strlen($str)."<br>"; echo substr($str,0,12)."<br>"; echo mb_strlen($str,"UTF8")."<br>"; echo mb_substr($str,0,12,"UTF8")."<br>"; ?>
显示结果如下
34 107sadf网� 16 107sadf网站工作室
The strlen() function returns the length of bytes occupied by the string. An English letter, number, and various symbols all occupy one byte, and their lengths are equal. is 1. A Chinese character occupies two bytes, so the length of a Chinese character is 2. For a UTF-8 Chinese character, it will be treated as having a length of 3. <br>
怎么准确的计算字符串的长度呢?这里,得引入另外一个函数mb_strlen()。mb_strlen()函数的用法与strlen()几乎一摸一样,只是多了一个指定字符集编码的参数。函数原型为:
mb_substr也同样的原理注:mb_strlen与mb_substr并不是PHP的核心函数,使用前需要打开php.ini中的extension=php_mbstring.dll这一项 方法二: <?php header("Content-Type: text/html; charset=utf-8"); $str="107sadf网站工作室欢迎您!"; function chinesesubstr($str,$start,$len){ $strlen = $len - $start; //定义需要截取字符的长度 for($i=0;$i<$strlen;$i++){ //使用循环语句,单字截取,并用$tmpstr.=$substr(?,?,?)加起来 if(ord(substr($str,$i,1))>0xa0){ //ord()函数取得substr()的第一个字符的ASCII码,如果大于0xa0的话则是中文字符 $tmpstr.=substr($str,$i,3); //设置tmpstr递加,substr($str,$i,3)的3是指三个字符当一个字符截取(因为utf8编码的三个字符算一个汉字) $i+=2; } else{ //其他情况(英文)按单字符截取 $tmpstr.=substr($str,$i,1); } } return $tmpstr;} echo chinesesubstr($str,0,12)."<br>"; ?>
The final result is displayed as:
107sadf网站
<br>
The above is the detailed content of What should I do if Chinese garbled characters appear when intercepting substr?. For more information, please follow other related articles on the PHP Chinese website!