我有很多链接出了一个foreach。每个的foreach输出一些DOM树,如:php preg_replace两个最后一个链接
<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>
,而不是我预期的。如何做得好?谢谢。
仍然无法正常工作,请参阅我的更新代码,还导出除link1之外的内容。 –
@鱼人,现在它应该工作 – onatm