Tonight, when you write the form validation class for the framework, you need to determine whether a string length is within a specified interval, and naturally think of the strlen function in PHP.
The code is as follows |
|
$str = ' Hello world! '; echo strlen ($STR); Output 12
|
Test Chinese
code as follows |
|
$str = ' Hello, world! '; Echo strlen ($STR);//GBK or GB2312 output 12,utf-8 under output. |
PHP built-in string length function strlen cannot handle Chinese strings correctly, it only gets the number of bytes that the string occupies. For the Chinese encoding of GB2312, strlen get the value is twice times the number of Chinese characters, and for UTF-8 encoded in Chinese, is 3 times times the difference (in UTF-8 encoding, a Chinese character accounted for 3 bytes).
The following example is excerpted from the famous WordPress, very accurate Oh, it is also important to note that this function is only applicable to utf-8 encoding strings.
The code is as follows |
|
function Utf8_strlen ($string =null) { To decompose a string into a cell Preg_match_all ("/./us", $string, $match); Returns the number of units return count ($match [0]); }
|
However, the above code in the UTF-8 encoding can not handle the gbk/gb2312 Chinese string, because the gbk/gb2312 character will be recognized as two characters and the calculation of the number will double, so I think of such a way:
The code is as follows |
|
$tmp = @iconv (' GBK ', ' utf-8 ', $str); if (!empty ($tmp)) { $str = $tmp; } Preg_match_all ('/./us ', $str, $match); echo Count ($match [0]); |
Compatible with gbk/gb2312 and UTF-8 codes, passed through a small amount of data, but not determined to be completely correct
http://www.bkjia.com/PHPjc/727579.html www.bkjia.com true http://www.bkjia.com/PHPjc/727579.html techarticle tonight, when you write the form validation class for the framework, you need to determine whether a string length is within a specified interval, and naturally think of the strlen function in PHP. The code is as follows $str = ' Hello wo ...