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.
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.
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.
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!