我在 php 中的正则表达式无法正常工作,但确实可以 RegexPal.com 工作


My regexp in php is not working correctly, but does work at RegexPal.com

在名为"ugh.php"的php文件中运行以下代码时,我得到以下输出:

NO, match: a      <- This is correct
YES, match: 123   <- This is correct
YES, match: 1,23  <- This is NOT correct
YES, match: 1.23  <- This is NOT correct
YES, match: 1,234 <-This is correct
YES, match: 1234  <-This is correct

我的 rexexp 的目标是允许在 html 表单字段中输入货币(仅限整数美元,逗号是可选的(。 我已经在上面指出了什么是有效的,什么是无效的。

但是,当我在以下网站上输入我的正则表达式时:http://www.regexpal.com/1,23 和 1.23 都表示不匹配,这是正确的响应。

<?php
$curency = array("a", "123", "1,23", "1.23", "1,234", "1234");
foreach ($curency as $item)
{
    if ( preg_match("/'b'd{1,3}(?:,?'d{3})*'b/", $item) )
    {
        echo 'YES, match: ' . $item . '<br>';
    }
    else
    {
        echo 'NO, match: ' . $item . '<br>';
    }   
}
?>

为什么当我在 php 文件中测试它们时,这些不指示"否,匹配"?

谢谢话筒

不要使用单词边界,而是使用字符串的开头/结尾 ^/$ 锚点:

preg_match("/^'d{1,3}(?:,?'d{3})*$/", $item)

/'b'd{1,3}(?:,?'d{3})*'b/ 的问题在于字符串 "1,23"/"1.23" 将部分匹配并返回 true。通过使用锚点 ^/$ ,您将检查字符串的开头到结尾以查看整个字符串是否匹配。