教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 php截取utf8或gbk编码中英文字符串

php截取utf8或gbk编码中英文字符串

发布时间:2018-02-25   编辑:jiaochengji.com
本文介绍了php截取字符串的方法,php自带strlen是返回的字节数,对于utf8编码的中文返回时3个,不满足需求,本文分享一个好用的字符串截取代码。

本节内容:
php 字符串截取代码。

微博的发言有字数限制,其计数方式是,中文算2个,英文算1个,全角字符算2个,半角字符算1个。
php中自带strlen是返回的字节数,对于utf8编码的中文返回时3个,不满足需求。
mb_strlen 可以根据字符集计算长度,比如utf8的中文计数为1,但这不符合微博字数限制需求,中文必须计算为2才可以。

找到一个discuz中截取各种编码字符的类,改造了下,已经测试通过.其中参数$charset 只支持gbk与utf-8。

代码:
 

复制代码 代码示例:

<?php
//字符串截取
$a = "s@@你好";
var_dump(strlen_weibo($a,'utf-8'));
结果输出为8,其中字母s计数为1,全角@计数为2,半角@计数为1,两个中文计数为4。源码如下:

//截取字符串的函数代码
function strlen_weibo($string, $charset='utf-8')
{
    $n = $count = 0;
    $length = strlen($string);
    if (strtolower($charset) == 'utf-8')
    {
        while ($n < $length)
        {
            $currentByte = ord($string[$n]);
            if ($currentByte == 9 ||
                $currentByte == 10 ||
                (32 <= $currentByte && $currentByte <= 126)) // www.jbxue.com
            {
                $n++;
                $count++;
            } elseif (194 <= $currentByte && $currentByte <= 223)
            {
                $n += 2;
                $count += 2;
            } elseif (224 <= $currentByte && $currentByte <= 239)
            {
                $n += 3;
                $count += 2;
            } elseif (240 <= $currentByte && $currentByte <= 247)
            {
                $n += 4;
                $count += 2;
            } elseif (248 <= $currentByte && $currentByte <= 251)
            {
                $n += 5;
                $count += 2;
            } elseif ($currentByte == 252 || $currentByte == 253)
            {
                $n += 6;
                $count += 2;
            } else
            {
                $n++;
                $count++;
            }
            if ($count >= $length)
            {
                break;
            }
        }
        return $count;
    } else
    {
        for ($i = 0; $i < $length; $i++)
        {
            if (ord($string[$i]) > 127)
            {
                $i++;
                $count++;
            }
            $count++;
        }
        return $count;
    }
}

您可能感兴趣的文章:
php中英文混排字符串截取方法
php截取中文字符串(无乱码)方法
php截取字符串(无乱码 utf8)
php如何截取字符串后四位
php截取字符串长度函数详解
php分割GBK中文乱码的解决方法
截取中文字符的函数-csubstr
php截取中文字符串乱码如何解决呢
php字符串截取(substr的应用与扩展)
php截取字符串实例代码

关键词: php编码  php字符串  字符串截取   
[关闭]
~ ~