2

I would like to add links around image tags with preg_replace().

Before:

<img href="" src="" alt="" />

After:

<a href="" ..><img href="" src="" alt="" /></a>

I would greatly appreciate any help. Thank you very much.

1

2 Answers 2

4

Would this help?

$str = '<img href="" src="" alt="" />';

preg_replace('/(<img[^>]+>)/', '<a href="" ...>$1</a>', $str));

Also, preg_replace_callback gives you great power in terms of dynamically determining the actual contents of the <a> tag.

EDIT: To safeguard against the flaw @Amber pointed out, this pattern should help:

'#(<img[^>]+ alt="[^"]*" />)#'

YMMV with that, depending on the uniformity of your <img> tags. Is alt always present and the last attribute, with single spaces around etc.

EDIT: Re: copying img's src to a's href:

preg_replace('#(<img[^>]+ src="([^"]*)" alt="[^"]*" />)#', '<a href="$2" ...>$1</a>', $str)

And again .. this is expecting uniformity from your original img tags. If they are created by you, you may be good as is. If not, you'll want to safeguard against missing attributes, varying order, double vs single quotes etc.

4
  • 2
    Aside from the fact that it fails if the alt-text of the image has a > in it.
    – Amber
    Jun 6, 2010 at 18:11
  • @partoa correct .. which is my I added the disclaimer "depending on ...". @rdanee knows his (EDIT: or her) exact situation best, I'm just trying to provide some pointers. Jun 6, 2010 at 19:15
  • Thanks! Could you tell also how could I copy the img's src to the a's href?
    – rdanee
    Jun 6, 2010 at 19:17
  • Thanks! Copying the img's src to the a's href is not working on my case. Everything else works perfectly.
    – Cristal
    Nov 9, 2018 at 6:48
0

It seams you are trying to give a "larger" version of an image upon click. If that is the case I would go with javascript.

In that scenario the link is not relevant to the site's content and functionality and only serves to enhance the user experience so it fits very well on the enhance-the-user-experience javascript type.

A jQuery example would be more or less like this (note that I added the can-click class to better control which image you want clicked):

$(function(){
    // get all images that have 'can-click' class
    $('img.can-click').each(function(){
        // adds the custom cursor pointer to give the user clicking feedback
        $(this).css('cursor', 'pointer');

        // your clicking handle goes here
        $(this).click(function(){
            // you can set up the image on a light-box, to a new tab, etc...
        });

    });
});

This code has not been tested.

Hope it helps!

1
  • Thank you! It's really useful, however I would stick to my original sollution :(
    – rdanee
    Jun 6, 2010 at 19:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.