PHP中的初学者正则表达式。一些讨厌的人物

时间:2013-04-16 21:52:47

标签: php regex

我需要将一些代码从VB.NET重写为PHP:

Dim price as String = Regex.Match(html, "id=""price"">&pound;\d+.\d+</span>").Value.Replace("id=""Acashprice"">&pound;", "").Replace("</span>", "")

所以我试图从正则表达式获得一个匹配:

id="price">&pound;\d+.\d+</span>

然而,无论我如何格式化它,我总是被告知它是无效的 - (即不允许反斜杠,或者什么是p?)。我想我可能必须将preg_quote与preg_match结合使用,但我也无法使用它。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

这应该做的工作:

preg_match('/(?<=id="price">)&pound;\d+.\d+/', '<span id="price">&pound;55.55</span>', $m);
print_r($m);

<强>输出:

Array
(
    [0] => &pound;55.55
)

更可靠的正则表达式如下:

$str = '<span id="price">&pound;11.11</span>
<span id="price">&pound;22</span>
<span id="price"> &pound; 33 </span>
<span      id  =  "price"   >      &pound; 44     </span>
<span      id=\'price\'   >      &pound; 55     </span>
<span class="component" id="price"> &pound; 67.89 </span>
<span class="component" id="price" style="float:left"> &pound; 77.5 </span>
<span class="component" id="price" style="float:left:color:#000"> £77.5 </span>
';
preg_match_all('/<span.+?id\s*=\s*(?:"price"|\'price\').*?>\s*((?:&pound;|£)\s?\d+(?:.\d+)?)\s*<\/span>/is', $str, $m);

print_r($m[1]);

<强>输出:

Array
(
    [0] => &pound;11.11
    [1] => &pound;22
    [2] => &pound; 33
    [3] => &pound; 44
    [4] => &pound; 55
    [5] => &pound; 67.89
    [6] => &pound; 77.5
    [7] => £77.5
)