Home > Backend Development > PHP Tutorial > 【PHP】substr的应用细节注意

【PHP】substr的应用细节注意

WBOY
Release: 2016-06-13 10:58:47
Original
794 people have browsed it

【PHP】substr的使用细节注意

  作者:zhanhailiang 日期:2012-12-06
Copy after login

substr只能用于截取单字节编码的字符串, 在使用substr去截取多字节的字符串有可能会出现乱码:

例:

<span class="re0" style="color:rgb(0,0,255)">$a</span> <span class="sy0" style="color:rgb(102,204,102)">=</span> <span class="st0" style="color:rgb(255,0,0)">"百度一下,你是zhan"</span><span class="sy0" style="color:rgb(102,204,102)">;</span><span class="co2" style="color:rgb(128,128,128); font-style:italic">#echo substr($a, 0, 5).PHP_EOL; // 乱码: 百庍</span><span class="co2" style="color:rgb(128,128,128); font-style:italic">#echo substr($a, 0, strlen($a)); // 使用substr截断字符串,若完整截取整个字段时,则不会乱码</span><span class="co1" style="color:rgb(128,128,128); font-style:italic">// 最佳解决方案</span><span class="kw1" style="color:rgb(177,177,0)">echo</span> <span class="kw3" style="color:rgb(0,0,102)">mb_substr</span><span class="br0" style="color:rgb(102,204,102)">(</span><span class="re0" style="color:rgb(0,0,255)">$a</span><span class="sy0" style="color:rgb(102,204,102)">,</span> <span class="nu0" style="color:rgb(204,102,204)">0</span><span class="sy0" style="color:rgb(102,204,102)">,</span> <span class="nu0" style="color:rgb(204,102,204)">10</span><span class="sy0" style="color:rgb(102,204,102)">,</span> <span class="st0" style="color:rgb(255,0,0)">"UTF-8"</span><span class="br0" style="color:rgb(102,204,102)">)</span><span class="sy0" style="color:rgb(102,204,102)">;</span> <span class="co1" style="color:rgb(128,128,128); font-style:italic">// 百度一下,你是zha</span>
Copy after login

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