phphtmlreplacehtml-parsingpreg-replace

Change the attribute values and text of <a> tags


On my forum when an image is uploaded it will gain the follow html:

<a target="_blank" href="attachment.php?aid=1" rel="nofollow">zebra.bmp</a>

In order to use a plugin I have installed, I need to match those kind of html and change them to:

<a href="attachment.php?aid=1" rel="fancyzoom">zebra.bmp</a>

On the plugin it already does some conversion, example:

$page=preg_replace('/\<a rel="nofollow" href="attachment.php\?aid=([0-9]+)" target="_blank"\>\<img/Usi','<a href="attachment.php?aid=$1" rel="fancyzoom"><img',$page);

Now I am trying to catch the html I posted in the begin of my question

$page=preg_replace('/\<a target="_blank" href="attachment.php\?aid=([0-9]+)" rel="nofollow"\>([a-zA-Z0-9_- ]+)\.(jpg|jpeg|gif|png|bmp|tif|tiff)\<\/a\>/Usi','<a href="attachment.php?aid=$1" rel="fancyzoom">$2.$3</a>',$page);

But the above does not seem to work is it because of the OR parenthesis ? Is there a way to make such replace where I just want the files ending with the above image extensions ?


Solution

  • You only have to escape the minus:

    $page=preg_replace('/\<a target="_blank" href="attachment.php\?aid=([0-9]+)" rel="nofollow"\>([a-zA-Z0-9_\- ]+)\.(jpg|jpeg|gif|png|bmp|tif|tiff)\<\/a\>',$page);
    

    Also see my demo.

    === UPDATE ===

    $page=preg_replace('/\<a.*?href="attachment.php\?aid=([0-9]+)".*?\>([a-zA-Z0-9_\- ]+)\.(jpg|jpeg|gif|png|bmp|tif|tiff)\<\/a\>/Usi','<a href="attachment.php?aid=$1" rel="fancyzoom">$2.$3</a>',$page);
    

    My new demo.