Home > php教程 > php手册 > php mb_strlen()中英混体字符截取代码

php mb_strlen()中英混体字符截取代码

WBOY
Release: 2016-06-13 09:54:58
Original
1136 people have browsed it

注:如果在用mb_strlen出现fatal error: call to undefined function mb_strlen,这种问题你要可以用php教程info()看一下有没有装载mbstring,如果没有,尝试将php_mbstring.dll复制到%windows%目录下。

文件编码 utf-8

$var = '中文字符abc';
mb_strlen($var, 'utf-8'); // 输出7 中文英文都占一个字节
mb_strlen($var); // 输出15 中文占3个字节 英文占一个字节
mb_strlen($var, 'gbk'); // 输出9 不正常

取全部中文

function utf8substr($str, $from, $len)
{
return preg_replace('#^(?:[x00-x7f]|[xc0-xff][x80-xbf]+){0,'.$from.'}'.
'((?:[x00-x7f]|[xc0-xff][x80-xbf]+){0,'.$len.'}).*#s',
'$1',$str);
}

中文与英混体截取代码

function gb2312_strlen($string)
{
$str_len = strlen($string);
$str_count = 0;
for($j = 0; $j {
   if(ord($string{$j})    {
    $str_count += 1;
    continue;
   }
   else
   {
    if(ord($string{$j+1}) > 127)
    {
     $str_count += 1;
     $j++;
     continue;
    }
    else
    {
     $str_count += 1;
     continue;
    }
   }
}
return $str_count;
}
$str = "开s d"; 
echo gb2312_strlen($str);

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