PHP regular expression to determine string Encoding

Source: Internet
Author: User

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.

  1. <? Php
  2. $ Action = trim ($ _ get [action]);
  3. If ($ action = "sub ")
  4. {
  5. $ Str = $ _ post [dir];
  6. // If (! Preg_match ("/^ [". chr (0xa1 ). "-". chr (0xff ). "a-za-z0-9 _] $/", $ str) // gb2312 Regular Expression of Chinese characters, letters, numbers, underscores (_)
  7. If (! Preg_match ("/^ [x {4e00}-x {9fa5} a-za-z0-9 _] $/u", $ str) // Regular Expression of UTF-8 Chinese characters, letters, numbers, underscores (_)
  8. {
  9. Echo "<font color = red> The [". $ str. "] You entered contains illegal characters </font> ";
  10. }
  11. Else
  12. {
  13. Echo "<font color = green> The [". $ str. "] You entered is completely legal. Pass! </Font> ";
  14. }
  15. }
  16. ?>
  17. <Form method = "post" action = "">
  18. Input characters (numbers, letters, Chinese characters, and underlines ):
  19. <Input type = "text" name = "dir" value = "">
  20. <Input type = "submit" value = "submit">
  21. </Form>

Gbk:
Preg_match ("/^ [". chr (0xa1 ). "-". chr (0xff ). "a-za-z0-9 _] $/", $ str); // gb2312 Regular Expression of Chinese characters, letters, numbers, underscores (_)

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.