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

php中英文字符串长度截取的例子

WBOY
Release: 2016-05-25 16:45:09
Original
1191 people have browsed it

使用此方法之前,请在php.ini中开启php_mbstring.dll扩展,将extension前面的;分号去掉即可,很多截取中文字符串的方法,大多不能实现按中文个数来截取所要的字符,以下代码可以实现:

<?php
mb_internal_encoding(&#39;UTF-8&#39;);
$str = "中文测试chineseTest";
header(&#39;content-type:text/html; charset=UTF-8&#39;);
echo mb_strlen($str);
echo &#39;<br/>&#39;;
echo mb_substr($str, 1, 6);
?>
Copy after login

输出结果:15 文测试chi

上面只是测试,下面整理例子,代码如下:

<?php
/*mb_string方法截取字符串长度
 * $arr_str 数组或字符串
 * $tlen 截取长度
 * $fleid 要截取的字段(数组形式)
*/
header(&#39;Content-Type: text/html; charset=utf-8&#39;);
function interception($arr_str, $tlen, $fleid = &#39;&#39;) {
    //判断是否是数组
    if (is_array($arr_str)) {
        //将数组下标重新排列
        foreach ($arr_str as $key => $val) {
            for ($k = 0; $k < count($fleid); $k++) {
                $content = $arr_str[$fleid[$k]];
                //判断是否大于指定的长度
                if (mb_strlen($content, &#39;utf-8&#39;) > $tlen) {
                    $arr_str[$fleid[$k]] = mb_substr($content, 0, $tlen, &#39;utf-8&#39;) . &#39;...&#39;;
                }
            }
        }
    }
    //判断是否是字符串
    elseif (is_string($arr_str)) {
        if (mb_strlen($arr_str, &#39;utf-8&#39;) > $tlen) {
            $arr_str = mb_substr($arr_str, 0, $tlen, &#39;utf-8&#39;) . &#39;...&#39;;
        }
    }
    return $arr_str;
}
//使用示例
//数组示例
$array = array(
    &#39;ha&#39; => &#39;哈尔滨市&#39;,
    &#39;bei&#39; => &#39;地球中国北京市&#39;,
);
//字符串示例
$string = &#39;中国的互联网:商业化很牛,公共服务几乎没有谢文&#39;;
$string2 = &#39;abcdefghijkl&#39;;
print_r(interception($array, 2, array(
    &#39;ha&#39;,
    &#39;bei&#39;
)));
echo &#39;<br />&#39; . interception($string, 5);
echo &#39;<br />&#39; . interception($string2, 5);
?>
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 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!