Regular Expression to identify Chinese characters (UTF-8 & gbk encoding is automatically recognized)
The following example program is a php Regular Expression program that correctly matches utf8 or gbk Chinese. It can accurately identify Chinese Characters in different encoding conditions.
- <? Php
- $ Action = trim ($ _ get [action]);
- If ($ action = "sub ")
- {
- $ Str = $ _ post [dir];
- // If (! Preg_match ("/^ [". chr (0xa1 ). "-". chr (0xff ). "a-za-z0-9 _] $/", $ str) // gb2312 Regular Expression of Chinese characters, letters, numbers, underscores (_)
- If (! Preg_match ("/^ [x {4e00}-x {9fa5} a-za-z0-9 _] $/u", $ str) // Regular Expression of UTF-8 Chinese characters, letters, numbers, underscores (_)
- {
- Echo "<font color = red> The [". $ str. "] You entered contains illegal characters </font> ";
- }
- Else
- {
- Echo "<font color = green> The [". $ str. "] You entered is completely legal. Pass! </Font> ";
- }
- }
- ?>
- <Form method = "post" action = "">
- Input characters (numbers, letters, Chinese characters, and underlines ):
- <Input type = "text" name = "dir" value = "">
- <Input type = "submit" value = "submit">
- </Form>
Gbk:
Preg_match ("/^ [". chr (0xa1 ). "-". chr (0xff ). "a-za-z0-9 _] $/", $ str); // gb2312 Regular Expression of Chinese characters, letters, numbers, underscores (_)