Home  >  Article  >  Backend Development  >  php mb_strlen() Chinese and English mixed character interception code_PHP tutorial

php mb_strlen() Chinese and English mixed character interception code_PHP tutorial

PHP中文网
PHP中文网Original
2016-07-13 10:54:201159browse

注:如果在用mb_strlen出现fatal error: call to undefined function mb_strlen,这种问题你要可以用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 < $str_len; $j++)
{
   if(ord($string{$j}) < 127)
   {
    $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);


Statement:
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