Introduction to php Regular Expression matching for Chinese Characters

Source: Internet
Author: User
Tags php regular expression

Php Regular Expression matches Chinese characters!

/^ [\ X {4e00}-\ x {9fa5}] + $/u

The above regular expression has plagued many php programmers.Regular Expression matching Chinese Characters

You may think it is very simple. In fact, different codes and different programming languages are slightly different, and you will not be able to get the correct results if you do not pay attention to them.

The following is an example of UTF-8 encoding:
$ Str="Chinese characters";
If (Preg_match("/^ [\ X {4e00}-\ x {9fa5}] + $/u",$ Str)){
Print ("This string is all Chinese");
} Else {
Print ("Not all strings are Chinese");
}

The following example containsExample:

<? 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))// UTF-8, Chinese characters, letters, numbers, underscores, regular expressions
{
Echo"<Font color = red> [".$ Str."] Contains illegal characters </font>";
}
Else
{
Echo"<Font color = green> [".$ Str."] Completely legal, pass! </Font>";
}
}
?>
<Form method = "POST" action = "? Action = sub ">
Input characters (numbers, letters, Chinese characters, and underlines ):
<Input type = "text" name = "dir" value = "">
<Input type = "submit" value = "submit">
</Form>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.