preg_replace正则表达式替换特定标记内的链接

时间:2017-06-10 07:42:57

标签: replace preg-replace href

我需要一个帮助,我想将href链接替换为特定div类中的链接。

<div id="slider1" class="owl-carousel owl-theme">
  <div class="item">
    <div class="imagens">
      <a href="http://oldsite.com/the-fate-of-the-furious"><img src="https://image.oldste.org" alt="The Fate of the Furious" width="100%" height="100%" /></a>
      <span class="imdb">
        <b class="icon-star"></b> N/A
      </span>
    </div>
    <span class="ttps">The Fate of the Furious</span>
    <span class="ytps">2017</span>
  </div>
</div>

我希望将http://oldsite.com/更改为http://newsite.com/?id=

我想要像

这样的href链接
<a href="http://newsite.com/?id=the-fate-of-the-furious">

请帮我处理preg_replace正则表达式。

由于

2 个答案:

答案 0 :(得分:0)

这可能会对你有所帮助

     $content = get_the_content();
     $pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
     $newurl = get_permalink();
     $content = preg_replace($pattern,$newurl,$content);

     echo $content;

答案 1 :(得分:0)

Lookbehinds过于昂贵,使用\K启动全字符串匹配并避免捕获组。

<a href="\K[^"]+\/这种模式非常有效。我应该声明这个模式将匹配所有<a href网址。它也会贪婪地匹配,直到它找到url中的最后一个/ - 我认为你的输入样本没问题。

Pattern Demo

代码(PHP Demo):

$in='<div id="slider1" class="owl-carousel owl-theme">
<div class="item">
<div class="imagens">
<a href="http://oldsite.com/the-fate-of-the-furious"><img src="https://image.oldste.org" alt="The Fate of the Furious" width="100%" height="100%" /></a>
<span class="imdb"><b class="icon-star"></b> N/A</span>
</div>
<span class="ttps">The Fate of the Furious</span>
<span class="ytps">2017</span>
</div>';

echo preg_replace('/<a href="\K[^"]+\//','http://newsite.com/?id=',$in);

输出:

<div id="slider1" class="owl-carousel owl-theme">
<div class="item">
<div class="imagens">
<a href="http://newsite.com/?id=the-fate-of-the-furious"><img src="https://image.oldste.org" alt="The Fate of the Furious" width="100%" height="100%" /></a>
<span class="imdb"><b class="icon-star"></b> N/A</span>
</div>
<span class="ttps">The Fate of the Furious</span>
<span class="ytps">2017</span>
</div>