Home  >  Article  >  php教程  >  php substr,iconv_substr,mb_substr

php substr,iconv_substr,mb_substr

WBOY
WBOYOriginal
2016-06-13 09:34:07837browse

php进行中文字符串的截取时,会经常用到二个函数iconv_substr和mb_substr,对这二个函数应该如何选择呢?参考下本文介绍的例子就明白了。

示例代码,用到了函数substr与iconv_substr,mb_substr

 1 <html>
 2 <head><meta charset='utf-8'>
 3 <title>截取中文字符串_脚本学堂_www.jbxue.comtitle>
 4 head>
 5 <body>
 6 php
 7 $str='123脚本学堂456欢迎大家的光临';
 8 echo substr($str,0,4);
 9 echo '
';
10 echo iconv_substr($str,0,4,'utf-8'); 11 echo '
';
12 echo mb_substr($str,0,4,'utf-8'); 13 ?> 14 body> 15 html>

 

说明:
以上代码用到了二个函数iconv_substr和mb_substr,均可以在当前字符下进行字符串截取,以达到中文字符截取的不乱码
应该如何选择呢?

1、iconv库在某些操作系统上可能运行不正确,需要安装GNU扩展库以保证它的正常运行。mb_substr函数的兼容性更好。
2、iconv函数会先将当前字符串转换为相应的编码再进行截取,而mb函数则是直接根据指定的编码进行截取(提供安全的多字节截取),所以mb函数的截取效率更高。
因此,mb_substr函数进行中文字符串的截取为最合适的选择。

Statement:
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