2014-09-01 28 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