php preg_replace两个的最后一个链接

时间:2011-10-21 23:50:45

标签: php regex

我有一个foreach的许多链接。每个foreach输出一些dom树像:

<span id="span1">
   <a(.*?)/test/(.*?)>word1</a>
</span>
<span id="span2">
   <a(.*?)/fold/(.*?)>word2</a>
</span>

现在我想替换两者的最后一个链接,将整个代码更改为:

<span id="span1">
   <a(.*?)/test/(.*?)>word1</a><!-- remain this link, do not replace. -->
</span>
<span id="span2">
   <a href="#" class="replaced" title="word2">word2</a>
</span>

我的preg_replace代码在这里:

$code = '<span><a href="http://localhost/test/index.html">test1</a></span><span><a href="http://localhost/fold/index.html">test2</a></span>';
echo  preg_replace('%href="(.*?)/fold/(.*?)"%', 'href="#" class="replaced" title="$2"', $code);

我想获得像

这样的代码
<span id="span1">
   <a href="http://localhost/test/index.html">test1</a>
</span>
<span id="span2">
   <a href="#" class="replaced" title="test2">test2</a>
</span>

但它会输出<span id="span1"><a href="#" class="replaced" title="index.html">word2</a></span>,而不是我预期的。怎么做好?感谢。

2 个答案:

答案 0 :(得分:1)

这将有效(修复):

preg_replace('(href="(.*?)/fold/(.*?)">(.*?)</a>)', 'href="#" class="replaced" title="$3">$3</a>', $code);

答案 1 :(得分:0)

感谢onam建议,最后,我使用simple_html_dom做出判断并获得我需要的代码。

$code = <<<EOT
<span id="span1"><a href="http://localhost/test/index1.html">word1</a></span><span id="span2"><a href="http://localhost/fold/index2.html">word2</a></span>
EOT;
$html = str_get_html($code);
if($html->find("span[id=span1]")) {
    foreach($html->find("span[id=span1]") as $data1)        
        $result1 =  $data1;
}
if($html->find("span[id=span2]")) {
    foreach($html->find("span[id=span2]") as $data2)
        $result2 = preg_replace('%href="(.*?)/fold/(.*?)">(.*?)</a>%', 'href="#" class="replaced" title="$3">$3</a>', $data2);
}
echo $result1.''.$result2;