Php - 检查字符串是否有中文字符的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4923319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:17:07  来源:igfitidea点击:

Php - regular expression to check if the string has chinese chars

phpregexstringcjk

提问by Adrian

I have the string $strand I want to check if it`s content has Chinese chars or not (true/false)

我有字符串$str,我想检查它的内容是否有中文字符(真/假)

$str = "赕就可消垻,只有当所有方块都被消垻时才可以过关";

can you please help me?

你能帮我么?

Thanks! Adrian

谢谢!阿德里安

回答by mario

You could use a unicode character class http://www.regular-expressions.info/unicode.html

您可以使用 unicode 字符类http://www.regular-expressions.info/unicode.html

preg_match("/\p{Han}+/u", $utf8_str);

This just checks for the presence of at least one chinese character. You might want to expand on this if you want to match the complete string.

这只是检查是否存在至少一个汉字。如果您想匹配完整的字符串,您可能需要对此进行扩展。

回答by eaglewu

@marioanswer is right!

@mario答案是对的!

For Chinese chars use this regex: /[\x{4e00}-\x{9fa5}]+/u

对于中文字符,请使用此正则表达式: /[\x{4e00}-\x{9fa5}]+/u

And Don't forget the umodifier!!!

并且不要忘记u修改器!!!

About umodifier reference

关于u修改器参考

TKS to mario

TKS 到马里奥

回答by Newton Singh

preg_match("/^\p{Han}{2,10}+$/u", $str);

Use /^\p{Han}{2,10}+$/uregex which allows Chinese character only.

使用/^\p{Han}{2,10}+$/u正则表达式,只允许汉字。

  1. It allows chinese character only &
  2. It allows Minimum 2 character &
  3. It allows maximum 10 character
  1. 它只允许汉字 &
  2. 它允许至少 2 个字符 &
  3. 它允许最多 10 个字符

You can change minimum and maximum character by changing {2,10} as per your need.

您可以根据需要通过更改 {2,10} 来更改最小和最大字符。

\p& /uare very important to add please don't avoid to add it.

\p& /u添加非常重要,请不要避免添加。

回答by Mark Baker

This linkto a previous question on identifying simplified or traditional Chinese might give you some ideas... you don't actually specify which you mean, and I don't know Chinese well enough to recognise the difference

这个链接到上一个关于识别简体中文或繁体中文的问题可能会给你一些想法......你实际上并没有具体说明你的意思,而且我对中文的了解不够了解区别