Home > php教程 > php手册 > body text

利用PHP函数计算中英文字符串长度的方法

WBOY
Release: 2016-06-06 20:17:44
Original
1417 people have browsed it

这篇文章主要介绍了利用PHP函数计算中英文字符串长度的方法,实例对比了PHP函数实现方法与正则表达式的实现方法,具有一定的参考借鉴价值,需要的朋友可以参考下

本文实例讲述了利用PHP函数计算中英文字符串长度的方法。分享给大家供大家参考。具体实现方法如下:

一般来说大家知道英文字符占一个字节,而中文字符gbk占两个字符,utf8占三个字符,很多人印象中php计算字符串长度就是strlen()函数,其实不然,它计算的是字节的长度而非字符的长度,那么如何获取一个字符串中字符的长度呢?还有有mb_strlen().

具体代码如下:

复制代码 代码如下:

echo $str = 'PHP点点通'; 

echo strlen($str); //3*1+3*3=12 
echo mb_strlen($str, 'gb2312'); //3*1+3*2=9 
echo mb_strlen($str, 'utf-8'); //6


可恶的是,mb系列的函数并不是PHP核心函数,默认没有开启的,还有一个超简单的方法,通过正则将字符串分解为字符个体,计算字符的个数即为字符串的长度,代码如下:

复制代码 代码如下:

function _strlen($str) 

        preg_match_all("/./us", $str, $matches); 
        return count(current($matches)); 

 
echo _strlen("PHP点点通");  //6 
?>

希望本文所述对大家的PHP程序设计有所帮助。

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!