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
Php - regular expression to check if the string has chinese chars
提问by Adrian
I have the string $str
and 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
回答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正则表达式,只允许汉字。
- It allows chinese character only &
- It allows Minimum 2 character &
- It allows maximum 10 character
- 它只允许汉字 &
- 它允许至少 2 个字符 &
- 它允许最多 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添加非常重要,请不要避免添加。