如何用中文获得preg_match 2位数点(可选)? [重复]

问题描述 投票:2回答:2

这个问题在这里已有答案:

我试图找出preg_match的汉字。我可以用这样的方式得到汉字

preg_match("/^\p{Han}+/u", $message); //$message = '你好';

但是,有时两位数的数字。在这样的事情之前

$message = '01. 你好' //or '21. 你好'

所以,我的preg_match条件在此消息中不正确。如何用点检查这个可选的两位数?

php regex preg-match
2个回答
2
投票

尝试/\p{Han}+/gu像:

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

要么

preg_match_all("/\p{Han}+/u", $message,$result);

1
投票

您能看看以下用于匹配和提取中文字符的php原型代码吗?如果它符合预期,请告诉我。

$ more test.php test2.php
::::::::::::::
test.php
::::::::::::::
<?php
$string = 'abc 123 車飛行 abc 5344';
$pattern = '/[^\p{Han}]/u';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
?>
::::::::::::::
test2.php
::::::::::::::
<?php
$message = "01. 你好";
echo preg_match_all("/^\p{Han}+$/u", $message);
echo "\n";
$message = "你好";
echo preg_match_all("/^\p{Han}+$/u", $message);
echo "\n";
$message = "01。你好";
echo preg_match_all("/^\p{Han}+$/u", $message);
echo "\n";
?>

两个代码的输出是:

1)为了从String中仅提取中文字符。

$ php test.php                                                                                                                                 
車飛行

2)为了验证字符串确实只包含中文字符。

$ php test2.php                                                                                                                                
0
1
0
© www.soinside.com 2019 - 2024. All rights reserved.