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

php substr,iconv_substr,mb_substr

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

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

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

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

 

说明:
以上代码用到了二个函数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