hamed farhadi hamed farhadi - 10 days ago 5
PHP Question

Replacing href value of all <a> elemnts without link with .mp3 extention

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

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

like this output

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

Answer

Use a negative lookahead:

$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";
$pattern = "/(?<=href=(\"|'))[^\"']+\.(?!(?:mp3|zip))\w+(?=(\"|'))/";
//      ^                      here __^^^^^^^^^^^^^^^
$newstring = preg_replace($pattern,$newurl,$string);

echo $newstring;

Output:

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