【问题标题】:preg_replace regular expression to replace link within a particular tagspreg_replace 正则表达式替换特定标签内的链接
【发布时间】:2017-11-12 05:50:14
【问题描述】:

我需要帮助,我只想将 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 正则表达式。

谢谢

【问题讨论】:

    标签: replace preg-replace href


    【解决方案1】:

    lookbehinds 太昂贵,使用\K 开始全字符串匹配并避免捕获组。

    &lt;a href="\K[^"]+\/ 这种模式会非常高效。我应该声明这个模式将匹配所有&lt;a href url。它也会贪婪地匹配,直到它在 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>
    

    【讨论】:

      【解决方案2】:

      这可能对你有帮助

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

      【讨论】:

        猜你喜欢
        • 2013-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多