Home php教程 php手册 利用PHP函数计算中英文字符串长度

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

May 26, 2016 am 08:21 AM

大家知道英文字符占一个字节,而中文字符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
Copy after login

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

<?php 
function _strlen($str) 
{ 
preg_match_all("/./us", $str, $matches); 
return count(current($matches)); 
} 
 
echo _strlen("PHP点点通");  //6
Copy after login

   


本文链接:

收藏随意^^请保留教程地址.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)