To judge whether a string is Chinese in php, we will follow this idea:
The code is as follows: |
Copy code |
<? Php $ Str = "php programming "; If (preg_match ("/^ [u4e00-u9fa5] + $/", $ str )){ Print ("all strings are Chinese "); } Else { Print ("Not all strings are Chinese "); } ?> |
However, it will soon be discovered that php does not support such expressions and an error is returned:
Warning: preg_match () [function. preg-match]: Compilation failed: PCRE does not support L, l, N, U,
Or u at offset 3 in test. php on line 3
At the beginning, I checked many times from google and tried to use the php regular expression for hexadecimal data.
Breakthrough in expression, found that in php, x represents hexadecimal data. So,
Convert to the following code:
The code is as follows: |
Copy code |
$ Str = "php programming "; If (preg_match ("/^ [x4e00-x9fa5] + $/", $ str )){ Print ("all strings are Chinese "); } Else { Print ("Not all strings are Chinese "); } |
It seems that no error is reported, and the result is correct. However, if you replace $ str with "programming", the result still shows "not all the strings are Chinese".
This is not accurate enough.
If you want to precisely match Chinese characters, that is, match Chinese characters only, or match Chinese characters with full-angle punctuation, you need to use different methods according to different encoding environments.
The following two types of commonly used encoding (gb2312, UTF-8)
The following are two examples:
The code is as follows: |
Copy code |
(1) ANSI programming environment: $ Strtest = "yyg Chinese character yyg "; $ Pregstr = "/([". chr (0xb0 ). "-". chr (0xf7 ). "] [". chr (0xa1 ). "-". chr (0xfe ). "]) +/I "; If (preg_match ($ pregstr, $ strtest, $ matchArray )){ Echo $ matchArray [0]; } // Output: Chinese characters (2) Utf-8 programming environment: $ Strtest = "yyg Chinese character yyg "; $ Pregstr = "/[x {4e00}-x {9fa5}] +/u "; If (preg_match ($ pregstr, $ strtest, $ matchArray )){ Echo $ matchArray [0]; } // Output: Chinese characters |