Home > php教程 > php手册 > body text

php截取字符串函数substr,iconv_substr,mb_substr示例以及优劣分析

WBOY
Release: 2016-06-13 09:33:59
Original
976 people have browsed it

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

复制代码 代码如下:




截取中文字符串_脚本之家_www.jb51.net


$str='123脚本之家456欢迎大家的光临';
echo substr($str,0,4);
echo '
';
echo iconv_substr($str,0,4,'utf-8');
echo '
';
echo mb_substr($str,0,4,'utf-8');
?>


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

应该如何选择呢?

1、iconv库在某些操作系统上可能运行不正确,需要安装GNU扩展库以保证它的正常运行。mb_substr函数的兼容性更好。

2、iconv函数会先将当前字符串转换为相应的编码再进行截取,而mb函数则是直接根据指定的编码进行截取(提供安全的多字节截取),所以mb函数的截取效率更高。

因此,mb_substr函数进行中文字符串的截取为最合适的选择。

Related labels:
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template