How to detect whether a string is UTF8 encoded code under PHP

Source: Internet
Author: User
Give a string, how to determine what it is encoded?

PHP has a function: mb_detect_encoding.

But this thing needs to have a mb_string library, not everywhere can use.

function Is_utf8 ($string) {return Preg_match ('%^ (?: [\x09\x0a\x0d\x20-\x7e] # ascii| [\XC2-\XDF] [\X80-\XBF] # Non-overlong 2-byte| \XE0[\XA0-\XBF][\X80-\XBF] # excluding overlongs| [\xe1-\xec\xee\xef] [\X80-\XBF] {2} # straight 3-byte| \XED[\X80-\X9F][\X80-\XBF] # excluding surrogates| \XF0[\X90-\XBF][\X80-\XBF]{2} # Planes 1-3| [\xf1-\xf3] [\X80-\XBF] {3} # planes 4-15| \XF4[\X80-\X8F][\X80-\XBF]{2} # Plane) *$%xs ', $string); }

Accuracy is basically the same as mb_detect_encoding, to be right together, to be wrong together.
Code detection is not possible 100% accurate, this thing has been able to basically meet the requirements.

  • 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: 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.