UTF.COM.CN

PHP: UTF-8兼容的substr()函数

作者:佚名 | 来源:网络 | 添加时间:2006-02-23 15:15:09 | 人气:1508

PHP: UTF-8兼容的substr()函数

把Nucleus改成了PHP编码后,发现一些功能,如RSS,LastComments插件等等由于要截取前…个字符做预览,结果造成了从UTF-8字符的中间截断,出现错误,这个函数可以很好的改善这个功能。

更好的实现方法当然是使用官方的mb_substr,但是需要在编译的时候指定参数,我等使用虚拟主机的只好用这个方法解决了。

<?
function utf8_substr($str,$start) { 
    /*
    UTF-8 version of substr(), for people who can’t use mb_substr() like me.
    Length is not the count of Bytes, but the count of UTF-8 Characters
    
    Author: Windix Feng
    Bug report to: windix(AT)gmail.com, http://www.douzi.org 

    - History -
    1.0 2004-02-01 Initial Version
    2.0 2004-02-01 Use PREG instead of STRCMP and cycles, SPEED UP!
    */ 

preg_match_all("/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/", $str, $ar);  

    if(func_num_args() >= 3) { 
        $end = func_get_arg(2); 
        return join("",array_slice($ar[0],$start,$end)); 
    } else { 
        return join("",array_slice($ar[0],$start)); 
    }
}
?> 
责任编辑:冬天来了
【字号: 】【去论坛讨论】【发表评论】【打印本文】【告诉好友】【关闭窗口
网友评论(评论内容只代表网友观点,与本站立场无关!)

姓名:

验证码: 点击刷新