1
4

5 回答 5

3

用正则表达式匹配汉字(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 并替换你想要的字符。

于 2019-01-25T06:03:53.277 回答
1

It looks like you probably want to replace the first '*' with '+' to ensure you have at least one matching character in the initial spot and you can drop the character group with '\s' and just use '.' as that will match any character. Also, if this is to be a complete line I would start the regex with '^' and end it with '$'.

于 2009-10-18T20:21:31.803 回答
1
  1. 如果开头应该只有一个汉字,去掉第一个'*'。
  2. 但是你应该保留'[.\s]',因为'.' 不匹配换行符(我认为)。
  3. 完成后,确保问题来自正则表达式而不是 php 代码。
于 2009-10-18T21:07:03.190 回答
0
/[\x{4e00}-\x{9fa5}][.\s]*\[\/m\][\x{4e00}-\x{9fa5}]/um
于 2009-10-19T08:51:45.910 回答
0
[\x{4e00}-\x{9fa5}]+.+\[\/m\][\x{4e00}-\x{9fa5}]

与您的描述相符:

[\x{4e00}-\x{9fa5}]+--> 4E00 和 9FA5 之间的一个或多个字符。

.+--> 一个或多个其他字符

\[\/m\]--> [/m]

[\x{4e00}-\x{9fa5}]--> 4E00 和 9FA5 之间的一个字符

于 2012-06-19T04:19:46.577 回答