PHP regular method example to determine whether a string contains Chinese characters

小云云
Release: 2023-03-21 12:04:01
Original
4318 people have browsed it

This article mainly shares with you examples of PHP regular methods to determine whether a string contains Chinese characters. I hope it can help you.

PHP regularity determines whether a string contains Chinese characters

The first method:

if (preg_match("/[\x7f-\xff]/", $str)) {
    //echo "有中文";
}else{
    //echo "没有中文";
}
Copy after login

The second method:

  if(preg_match ("/[\x{4e00}-\x{9fa5}]/u", $keyword)){
        // 汉字
        $where['goods_name like'] =  '%'.$keyword.'%';
   }else{
        // 拼音
        $where['pinyin like'] =  '%'.strtolower($keyword).'%';
   }
Copy after login

I have been searching online for a long time. Most of them are java and js methods, but using Java and js methods directly, old It was an error, but later I found out

Wrap both sides of "4e00" and "9fa5" with "{" and "}" respectively, and it worked

What should be noted here is: preg_match() When verifying Chinese, you need to add /u

I know utf-8 in php The final correct expression using regular expressions to match Chinese characters under encoding——/^[\x{4e00}-\x{9fa5}]+$/u, I know where the problem is. For other detailed rules, you can just change it yourself

Attach a piece of code

$str = "php入坑指南";
if (preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$str)) {
     print("该字符串全部是中文");
} else {
     print("该字符串不全部是中文");
}
Copy after login


Attached, double-byte character encoding range

1. GBK (GB2312/GB18030)
\x00-\xff GBK double-byte encoding range
\x20-\x7f ASCII
\xa1-\xff Chinese gb2312
\x80-\xff Chinese gbk

2. UTF-8 (Unicode)
\u4e00-\u9fa5 (Chinese)
\x3130-\x318F (Korean
\xAC00-\ xD7A3 (Korean)
\u0800-\u4e00 (Japanese)*/

Related recommendations:

js processing containing Chinese string example sharing

php Chinese string interception method example summary

Detailed example of parsing url function with Chinese characters in php

The above is the detailed content of PHP regular method example to determine whether a string contains Chinese characters. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template