2011-11-06 53 views
0

作爲一個簡單的例子,我試圖獲得所有包含電子郵件地址的dom對象。在PHP XPath中使用正則表達式 - >評估

$doc = new DOMDocument; 
    $doc->loadHTML($page); 

    $xpath = new DOMXPath($doc); 
    $body = $doc->getElementsByTagName('table')->item(0); 
    $query = "//text()[fn:matches(., '[\w\d\.-][email protected][\w\d\.-]+\.[a-zA-Z]{2,4}')]"; // 
    $entries = $xpath->evaluate($query, $body); // 
    foreach ($entries as $entry) { 
     echo "Found {$entry->textContent}<br>\n"; 
    } 

,我發現了錯誤:"DOMXPath::evaluate() [domxpath.evaluate]: xmlXPathCompOpEval: function matches bound to undefined prefix fn ..."

我也想盡了辦法

//text()[ 
    php:function('BooleanPregMatch', '[\w\d\.-][email protected][\w\d\.-]+\.[a-zA-Z]{2,4}', .) 
] 

沒有成功。

我一直沒能找到許多與fn:match或php:function相關的例子。任何援助將不勝感激。

+0

我可以建議用雙引號在matches()函數中嘗試嗎? – Scuzzy

+1

你讀過['DOMXPath :: registerPhpFunctions()'頁面](http://www.php.net/manual/en/domxpath.registerphpfunctions.php)嗎? – Phil

回答

4

fn:matches是XPath 2.0,在DOMXPath中,您有XPath 1.0。這就是爲什麼它不起作用,它不受支持。

有關php:function的示例,請參見DOMXPath::registerPhpFunctions的手冊頁。你需要有PHP 5.3來註冊函數。