Heim >Backend-Entwicklung >PHP-Tutorial >php substr,iconv_substr,mb_substr_PHP教程
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函数进行中文字符串的截取为最合适的选择。