[英]Matching Chinese characters with regular expressions (php)
您能指出我正则表达式中的错误吗?
/[\\x{4e00}-\\x{9fa5}]*[.\\s]*\\[\\/m\\][\\x{4e00}-\\x{9fa5}]/u
我的字符串以汉字( [\\x{4e00}-\\x{9fa5}]
)开头,后跟任意字符,并以'[/ m]'和另一个汉字结尾。 因此字符串可能看起来像:
我... some text goes here (contains any characters including spaces and new lines)... [/m]我
但不幸的是,我的正则表达式无法按预期工作。
看来您可能想用'+'替换第一个'*'以确保您在初始位置至少有一个匹配的字符,并且可以将字符组删除为'\\ s'并仅使用'。'。 因为它将匹配任何字符。 另外,如果要完整显示一行,我将以“ ^”开头的正则表达式,以“ $”结尾。
匹配汉字和正则表达式(php)
<?php
# this is our regx /\p{Han}+/u
$string='我... some text goes here (contains any characters including spaces and new lines)... [/m]我';
if(preg_match("/\p{Han}+/u", $string)){
echo "chinese here";
}
if(preg_match("/\p{Han}+/u", $string)){
#get all chinese characters in one array
preg_match_all('/\p{Han}+/u',$string,$matches);
print_R($matches[0]);
}
?>
这里的中国人
Array (
[0] => Array
(
[0] => 我
[1] => 我
)
)
您可以进行foreach并替换所需的字符。
[\x{4e00}-\x{9fa5}]+.+\[\/m\][\x{4e00}-\x{9fa5}]
符合您的描述:
[\\x{4e00}-\\x{9fa5}]+
-> 4E00和9FA5之间的一个或多个字符。
.+
->一个或多个其他字符
\\[\\/m\\]
-> [/ m]
[\\x{4e00}-\\x{9fa5}]
-> 4E00和9FA5之间的一个字符
/[\x{4e00}-\x{9fa5}][.\s]*\[\/m\][\x{4e00}-\x{9fa5}]/um
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.