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

PHP mb_strwidth在实际使用中的问题解析

WBOY
Release: 2016-06-13 11:07:19
Original
1208 people have browsed it

最近做的一个PHP网站项目新闻部分需要一个功能,按照标题的宽度截取字符串并在末尾添加“...”,首先想到的就是使用PHP的mb_字符串函数实现,mb_strimwidth,mb_strwidth,后发现如果标题中存在“”符号的时候,PHP mb_strwidth会将该符号认为是1个宽度,我纳闷了这个不是中文的双引号嘛,照理说肯定是宽字节的,长度应该是2个宽度,后查询“”unicode分别为u201C和u201D,不在中文字符的范围中,再查询unicode.org 的码表,发现u2000-u206F是通用符号的范围,此范围中的字符虽然都是宽字符的形式,但是PHP 的mb_函数却认为是1个宽度,没办法,只能靠自己了。

以下是实现的函数:

<ol class="dp-xml">
<li class="alt"><span><span>function truncString($str, $length)  </span></span></li>
<li><span>{  </span></li>
<li class="alt">
<span>$</span><span class="attribute">countLen</span><span>=</span><span class="attribute-value">0</span><span>;  </span>
</li>
<li>
<span>for($</span><span class="attribute">i</span><span>=</span><span class="attribute-value">0</span><span>;$i</span><span class="tag"><span class="tag-name">mb_strlen</span><span>($str);$i++)  </span></span>
</li>
<li class="alt"><span>{  </span></li>
<li><span>$countLen+=amb_strwidth(mb_substr($str,$i,1));  </span></li>
<li class="alt">
<span>if($countLen</span><span class="tag">></span><span>$length)  </span>
</li>
<li><span>return mb_substr($str,0,$i);  </span></li>
<li class="alt"><span>}  </span></li>
<li><span>return $str;  </span></li>
<li class="alt"><span>}  </span></li>
<li><span>function amb_strwidth($str_width)  </span></li>
<li class="alt"><span>{  </span></li>
<li>
<span>$</span><span class="attribute">count</span><span>=</span><span class="attribute-value">0</span><span>;  </span>
</li>
<li class="alt">
<span>for($</span><span class="attribute">i</span><span>=</span><span class="attribute-value">0</span><span>;$i</span><span class="tag"><span class="tag-name">mb_strlen</span><span>($str_width);$i++)  </span></span>
</li>
<li><span>{  </span></li>
<li class="alt"><span>//if(mb_substr($str_width,$i,1)=="xE2x80x9C"||mb_substr($str_width,$i,1)=='xE2x80x9D')  </span></li>
<li><span>//如果遇到u2000-u206F内的字符则将计数器加2  </span></li>
<li class="alt"><span>if(preg_match("/[x{2000}-x{206F}]/u",mb_substr($str_width,$i,1)))  </span></li>
<li><span>$count+=2;  </span></li>
<li class="alt"><span>else  </span></li>
<li><span>$count+=mb_strwidth(mb_substr($str_width,$i,1));  </span></li>
<li class="alt"><span>}  </span></li>
<li><span>return $count;  </span></li>
<li class="alt"><span>} </span></li>
</ol>
Copy after login

以上就是在使用PHP mb_strwidth时出现问题的具体解决办法,希望对大家起到一些帮助的作用。


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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!