2013-04-16 32 views
0

我需要重寫從VB.NET一些代碼到PHP: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結合使用,但我也無法使其工作。任何幫助將非常感激。

+0

向我們展示PHP代碼。正則表達式嘗試匹配價格標籤並插入一些自定義HTML。 – silkfire

+0

您應該可以在正則表達式中避免使用引號和'<', '>','/'符號(任何在正則表達式中有意義的特殊字符)! – adeneo

+0

所有正則表達式的作用是找到我感興趣的下載頁面的一部分。目前爲止唯一的代碼是:preg_match(「id =」Acashprice「> £ \ d +。\ d +」,$ page ,$匹配); \t \t $ price = $ matches [0];我知道這是錯誤的。 – drspa44

回答

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 
) 
+0

謝謝。這真的很有幫助。 :) – drspa44

+0

@ drspa44不客氣,我進一步調整了正則表達式:) – HamZa