php截取utf-8字符串乱码的方法

3次阅读

  用 php 截取 utf- 8 中文字符串乱码的解决方法:
    在 PHP 中截取 UTF- 8 编码的字符串时, 有可能碰到半字符的问题, 也就是乱码, 以下函数可以解决这个问题:function utf8_substr($str,$len)
    {
    for($i=0;$i<$len;$i++)
    {
    $temp_str=substr($str,0,1);
    if(ord($temp_str) > 127){
    $i++;
    if($i<$len){
    $new_str[]=substr($str,0,3);
    $str=substr($str,3);
    }
    }else {
    $new_str[]=substr($str,0,1);
    $str=substr($str,1);
    }
    }
    return join($new_str);
    }

正文完