Heim  >  Artikel  >  Backend-Entwicklung  >  【PHP】substr的应用细节注意

【PHP】substr的应用细节注意

WBOY
WBOYOriginal
2016-06-13 10:58:47722Durchsuche

【PHP】substr的使用细节注意

  作者:zhanhailiang 日期:2012-12-06

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>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:PHP装配eAcceleratorNächster Artikel:PHP施用DES进行加密和解密