2014-09-01 27 views
0

頁面代碼的鏈接,我想改變這種使用的preg_match:查找用的preg_match

<li class="fte_newsarchivelistleft" style="clear: both; padding-left:0px;"><a class="fte_standardlink fte_edit" href="news,2480143,3-kolejka-sezonu-2014-2015.html">3 kolejka sezonu 2014/2015&nbsp;&raquo;&raquo;</a></li> 
         <li class="fte_newsarchivelistright" style="height: 25px;">komentarzy: <span class="fte_standardlink">[0]</span></li> 

要這樣:

news,2480143,3-kolejka-sezonu-2014-2015.html 

我該怎麼辦呢?我試圖與preg_match但該鏈接太複雜...

回答

0

使用preg_match確實太複雜。正如在這個網站上多次提到的:正則表達式+ HTML混合不好。正則表達式不適合處理標記。 DOM解析器,然而是:

$dom = new DOMDocument;//create parser 
$dom->loadHTML($htmlString); 
$xpath = new DOMXPath($dom);//create XPath instance for dom, so we can query using xpath 
$elemsWithHref = $xpath->query('//*[@href]');//get any node that has an href attribtue 
$hrefs = array();//all href values 
foreach ($elemsWithHref as $node) 
{ 
    $hrefs[] = $node->getAttributeNode('href')->value;//assign values 
} 

在此之後,它是在處理的$hrefs值,這將是一個字符串數組,其中每一個都是一個href屬性的值的一個簡單的事情。

使用DOM解析器和XPath(向你展示它可以做什麼)的另一個例子:can be found here

要更換與href值的節點,這是一個簡單的問題:

  • 獲取父節點
  • 構建文本節點
  • 調用DOMDocument::replaceChild
  • 致電Finnishing了寫入一個文件,或saveHTMLsaveXML獲得DOM作爲一個字符串

一個例子:

$dom = new DOMDocument;//create parser 
$dom->loadHTML($htmlString); 
$xpath = new DOMXPath($dom);//create XPath instance for dom, so we can query using xpath 
$elemsWithHref = $xpath->query('//*[@href]');//get any node that has an href attribtue 
foreach ($elemsWithHref as $node) 
{ 
    $parent = $node->parentNode; 
    $replace = new DOMText($node->getAttributeNode('href')->value);//create text node 
    $parent->replaceChild($replace, $node);//replaces $node with $replace textNode 
} 
$newString = $dom->saveHTML(); 
+0

呀,這樣的作品,謝謝:) – user3898993 2014-09-01 15:19:48

+0

@ user3898993:要是你想的正則表達式處理標記時,只記得:[它召喚Cthulhu](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)..這是一種傳說中的答案:) – 2014-09-01 15:21:23

+0

哈哈好吧,我會記得;) – user3898993 2014-09-01 16:44:09