2014-01-05 22 views
0

我試圖獲得href匹配某個正則表達式的標記的索引,但無論我嘗試的是拋出一個警告,說該表達式是無效的。這是一個例子。XPath/PHP - 返回索引匹配正則表達式的特定標記

$dom = new DOMDocument(); 
$dom->loadHTML($html); 
$url_check = testurl.com 
$finder = new DomXPath($dom); 

$finder->registerNamespace("php", "http://php.net/xpath"); 
$finder->registerPhpFunctions('preg_match'); 

//Updated to fix some errors, still invalid expression 
$index = $finder->evaluate("count((/ol[@id='rso']/li[not(@id) and @class = 'g' and h3[@class='r']/a[php:function('preg_match','/^(http://|https://|ftp://)?(www(\d+)?.)?($url_check)\/?$/', string(@href) > 0)]])/preceding-sibling::*)"); 

$html是存儲網頁的HTML字符串,其中包含這樣的事情

<ol id="wrap"> 
    <li class="list"> 
    <h3 class="j"> 
     <a href="http://xxxxxx.com">Not the one I'm trying to match</a>  
    </h3> 
    </li> 
    . 
    . 
    . 
    <li class="list"> 
    <h3 class="j"> 
     <a href="http://testurl.com">Click here</a>  
    </h3> 
    </li> 
</ol> 

任何建議表示讚賞,如果你知道一個更好的/更快的方式做到這一點感到自由分享:)

回答

0

我發現你的表達至少有三個問題:

  • preceding-siblings應該是單數,不是複數
  • count()函數沒有結束括號
  • $url_check = testurl.com沒有引號(應觸發語法錯誤)。

固定代碼:

$index = $finder->evaluate("count(/ol[@id='wrap']/li[@class = 'list']/h3[@class='j']/a[php:function('preg_match','/^(http://|https://|ftp://)?(www(\d+)?.)?($url_check)\/?$/', string(@href) > 0)]/preceding-sibling::li[@class='list'])"); 

此外,你給我們的示例HTML代碼不提供用於表達任何結果(各<a>元素沒有任何兄弟姐妹)。所以,即使有了這些修復,表達式仍然會返回0爲您的測試用例,這是正常的

+0

$ url_check引號是在我的實際代碼中,這是一個示例。我想要實現的是計算li的前面的兄弟,它包含一個具有滿足的屬性href的標籤。這是我第一次使用XPath,因此我很難處理語法 – davidaam

相關問題