如何编写正则表达式以匹配页面上的价格?

时间:2012-09-25 19:24:52

标签: php regex

您好我正在尝试从不同的URL获取产品的价格,我知道如何获取内容,但我很难写正则表达式函数,有人可以帮我写一个。它应匹配$后的任何数字,例如“$ 40”“$ 40.95”和“$ 45”

谢谢

2 个答案:

答案 0 :(得分:1)

$string = '
    Hi! This answer will cost you $10. 
    If you do not vote this answer up, it will cost you another in $1.23 or $ 2.45. 
    Be good and transfer me arround $12.45 bucks to my IBAN SI56 1234 4567 8901 234.
    Just joking, it is for free ;-)
';
preg_match_all('~(\$\h?\d+(\.\d+)?)~', $string, $matches);

echo "<pre>".print_r($matches[1],true)."</pre>";

这将输出:

Array
(
    [0] => $10
    [1] => $1.23
    [2] => $ 2.45
    [3] => $12.45
)

答案 1 :(得分:0)

您可以使用以下内容:

/(\$[0-9]+(\.[0-9]+)?)/