替换所有<a> elemnts without link with .mp3 extention

时间:2016-12-01 09:40:53

标签: php preg-replace

this is my created php code for Replac a href value to new url

 $string = "<a href='http://example.com/test'>click here</a>
 <a href='http://example.com/test.mp3'>the site</a>";
 $newurl = "http://newurl.com";
 $pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
 $newstring = preg_replace($pattern,$newurl,$string);
 echo $newstring;

now i want if links with .mp3 or .zip extentions not Replacing to new link

example : i want Replacing " http://example.com/post/1&#34;的href值到"http://myotherexample.com/test"      如果链接网址为"http://example.com/test.mp3"     不替换并显示genral url

喜欢这个输出

视图源:

<a href='http://myotherexample.com'>click here</a>
    <a href='http://example.com/test.mp3'>the site</a>

2 个答案:

答案 0 :(得分:0)

使用否定前瞻:

$string = "<p>Please <a href='http://example.com'>click here</a> to go to <a     href='http://example.com/test.mp3'>the site</a></p>";
$newurl = "http://myotherexample.com";

// Edit according to comment
$pattern = "/(?<=href=(\"|'))[^\"']+\.(?!(?:mp3|zip))(?:\/?\?[^\"']*)?(?=(\"|'))/";

$newstring = preg_replace($pattern,$newurl,$string);

echo $newstring;

<强>输出:

<p>Please <a href='http://myotherexample.com'>click here</a> to go to <a     href='http://example.com/test.mp3'>the site</a></p>

答案 1 :(得分:0)

(<a[^>]*?href\s*=\s*['"](?![^'"]*mp3))[^'"]*

这将与包含找不到<a...>的{​​{1}}的{​​{1}}相匹配。它会将文本捕获到开头的引号,然后匹配到结束引号,这样您就可以将URL更改为您想要的任何内容。

Example您可以使用网站左侧的code generator获取如何匹配/替换此内容的PHP版本。