我正在使用这个很棒的代码:Extract dollar amount from string - regex in PHP
在regex101.com上效果很好
但它并没有在我的代码中填充$ match,我不确定为什么(我的大脑是超级油炸的)
$price=38;
$dollar_regex = "/\$([0-9]+[\.]*[0-9]*)/";
$str = "Yes [Add $3.00]";
preg_match("/\$([0-9]+[\.]*[0-9]*)/", $str, $match);
$fee = $match[1];
echo "FEE is $fee. Changing price from $price to ";
$price = $price + $fee;
echo "$price<br>";
答案 0 :(得分:4)
正则表达式本身是正确的。它偶然发现了PHP字符串转义:
preg_match("/\$...
↑
单个反斜杠只是以双引号转义$
sigil。因此,正则表达式引擎会将其作为文字/$(...)/
接收。
所以要么使用两个反斜杠,要么将美元符号括在[$]
个charclass中以便于阅读。