hi,欢迎访问本站!
当前位置: 首页编程开发正文

php几种判断字符串长度的方法

墨初 编程开发 868阅读

php脚本中的内置函数 strlen(),mb_strlen(),iconv_strlen() 函数可以获取一串字符串的长度,但它们的使用场景是不同的,下面73so博客就详细的介绍一下。

关于中英字符串的长度

在不同的编码格式下,中文占的字节数是不一样的。

1、gbk编码下:每个中文占 2 个字节。 

2、UTF-8编码下:每个中文占 3 个字节

php strlen() 函数

php strlen() 函数返回的是字符串所占字节的长度,而不是字符串中字符的数量,简单来说就是以字节为单位返回字符串的长度!

例:strlen 在utf-8编码下获取字符串的长度

echo strlen('abcd');
// 4
echo strlen('博客');
// 6
echo strlen('73so.com博客');
// 14

例2:strlen 在gbk编码下获取字符串的长度

echo strlen('abcd');
// 4
echo strlen('博客');
// 4
echo strlen('73so.com博客');
// 12

php mb_strlen() 函数

php mb_strlen 返回的是字符的个数而不是字符占的字节,如果含有中文其返回的数量与函数的第二个参数设置的编码有关。

例1:在函数 mb_strlen() 中指定编码

$str = '博客';   
echo mb_strlen($str,'utf8');
// 2   
echo mb_strlen($str,'gbk');
// 3   
echo mb_strlen($str,'gb2312');
// 4

注:mb_strlen() 需要 mbstring 扩展的支持,如果不如果 mbstring 扩展那么此函数是无法使用的。

例2:使用 mb_strlen 函数是否可用

//判断1
if (function_exists('mb_strlen')) {
    // mb_strlen 函数可用
}
//判断2
if (function_exists('mb_strlen') && function_exists('mb_internal_encoding')) {
    // mb_strlen 函数可用
}

php iconv_strlen() 函数

iconv_strlen() 函数与 mb_strlen() 函数功能相似,但不同的是 iconv_strlen 不依赖 mbstring 扩展而且他处理的字符串编码必须与第二个参数指定的编码相同,否则返回 false

例:

echo iconv_strlen('abcd','utf-8');
// 4
echo iconv_strlen('73so.com博客','utf-8');
// 10
echo iconv_strlen('博客','utf-8');
// 2

例:

var_dump(iconv_strlen('abcd','utf-8'));
// int(4)
var_dump(iconv_strlen('73so.com','gbk2312'));
// bool(false)

php 自定义获取字符串长度的函数

例1:php 使用正规表达式获取字符串的长度

function utf8_strlen($string = null) 
{
    // 将字符串分解为单元
    preg_match_all("/./us", $string, $match);
    // 返回单元个数
    return count($match[0]);
}
echo utf8_strlen('abcd');  //4 
echo utf8_strlen('73so.com博客'); // 10

例2:利用 mb_strlen,iconv_strlen 三个函数获取字符串的长度

function get_StrLen($string)
{
    if (function_exists('mb_strlen') && function_exists('mb_internal_encoding')) {
        mb_internal_encoding('UTF-8');
        return mb_strlen($string);
    }
    if (function_exists('iconv_strlen') && function_exists('iconv_set_encoding')) {
        call_user_func('iconv_set_encoding', 'internal_encoding', "UTF-8");
        call_user_func('iconv_set_encoding', 'output_encoding', "UTF-8");
        return iconv_strlen($string);
    }
    return strlen($string);
}
echo get_StrLen('abcd');  //4 
echo get_StrLen('73so.com博客'); // 10
声明:无特别说明,转载请标明本文来源!
相关推荐