开发者

Add link around img tags with regexp

开发者 https://www.devze.com 2023-01-02 06:09 出处:网络
I would like to add links around image tags with preg_replace(). Before: <img href=\"\" src=\"\" alt=\"\" />

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

Before:

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

开发者_如何学GoAfter:

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


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号