简体   繁体   中英

php preg_replace the last link of two

I have many links out of one foreach. each foreach output some dom tree like:

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

Now I want to replace the last link of the two, change the whole code as:

<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>

My preg_replace code here:

$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);

I want get code like

<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>

But it will output <span id="span1"><a href="#" class="replaced" title="index.html">word2</a></span> , not as I expected. how to do well? thanks.

这将工作( 固定 ):

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

Thanks for onatm suggestion, finnally, I use simple_html_dom make a judge and get the code what I need.

$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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM