tags:

views:

98

answers:

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.

A: 

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.

Lauri Lehtinen
Aside from the fact that it fails if the alt-text of the image has a `>` in it.
Amber
Good point @Amber
Lauri Lehtinen
Now alt is required
partoa
@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.
Lauri Lehtinen
Thanks! Could you tell also how could I copy the img's src to the a's href?
@rdanee see my latest edit
Lauri Lehtinen
Yeah I saw it, thank you very much Lauri you are great : ))
A: 

By your question it seams you're trying to provide a larger image for the users on a specific set of images. If that is indeed the deal I would probably go with javascript.

It's not really a site link but a user-experience link so that fits into 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 example has not been tested.

Hope it helps!

Frankie
Thank you! It's really useful, however I would stick to my original sollution :(