How to calculate string length in php

怪我咯
Release: 2023-03-12 14:16:02
Original
10755 people have browsed it

This article mainly introduces the method of using PHP function to calculate the length of Chinese and English string. The example compares the PHP function implementation method with regular expression The implementation method has certain reference value. Friends who need it can refer to

. This article describes the method of using PHP functions to calculate the length of Chinese and English strings. Share it with everyone for your reference. The specific implementation method is as follows:

Generally speaking, everyone knows that English characters occupy one byte, while Chinese characters gbk occupies two characters, and utf8 occupies three characters. Many people have the impression that PHP calculates the length of a string by strlen( ) function, actually it is not the case. It calculates the length of bytes rather than the length of characters. So how to get the length of characters in a string? There is also mb_strlen().

The specific code is as follows:

The code is as follows:

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

What’s terrible is that the mb series functions are not PHP core functions. It is not turned on by default. There is also a super simple method to decompose the string into individual characters through regular expressions. Calculating the number of characters is the length of the string. The code is as follows:

The code is as follows:

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


The above is the detailed content of How to calculate string length in php. For more information, please follow other related articles on the PHP Chinese website!

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 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!