2017-06-10 9 views
-1

私は1つのヘルプが必要です、私は特定のdivクラス内の私のリンクにhrefリンクを置き換えたいです。preg_replace特定のタグ内のリンクを置き換える正規表現

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

はここで私は

<a href="http://newsite.com/?id=the-fate-of-the-furious"> 

がにpreg_replace正規表現で私を助けてくださいように、これらのhrefのリンクをしたいhttp://oldsite.com/

http://newsite.com/?id=に変更したいです。

おかげ

答えて

0

これはあなたがLookbehindsがあまりにも高価で

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

    echo $content; 
0

、fullstringの試合を開始し、キャプチャグループを避けるために\Kを使用するのに役立つことがあります。

<a href="\K[^"]+\/このパターンは非常に効率的です。このパターンはすべて<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> 
関連する問題