31

I want to make it so that any occurance of an image gets wrapped with a link to the image source

How can I write a pattern, in PHP so that I can find these variations, which are scattered throughout text coming from the database:

<img src='/dir/dir2/image1.jpg' alt='blah blah blah'>
<img src="/dir/dir2/image2.jpg" alt="blah blah blah" />
<img src="/dir/dir2/image3.jpg" />

In all cases, I want them to appear within an link.

2
  • 1
    So you are converting <img src="A"/> into <a href="A"><img src="A"/></a>? Commented Dec 16, 2010 at 2:00
  • 7
    Obligatory: stackoverflow.com/questions/1732348/… :) (In your case it's probably manageable, but Cthulu still applies.) Commented Dec 16, 2010 at 2:00

3 Answers 3

23

preg_replace("{<img\\s*(.*?)src=('.*?'|\".*?\"|[^\\s]+)(.*?)\\s*/?>}ims", '<a href=$2><img $1src=$2 $3/></a>', $str)

handles all non-practical cases

alt text

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks SHiNKiROU you are my hero
Aghghghghhhh!!! Regex-based HTML parsing!
bugged, as a regex approach is bound to be. this regex fails on <img data-license-src="foo.com/LICENSE" src="foo.com/img1.png"/> , it will link to the liecense rather than the image. seriously, use a friggin html parser, like DOMDocument.
12

My I recommend the PHP DOM with loadHTML() instead of regex?

http://php.net/dom

http://php.net/domdocument.loadhtml

1 Comment

Those are the good sites to use.
8

May I recommend using jQuery and use this snippet instead, it should be easier (and we all love jQuery to brute-force any problem ;] )

$('img').wrap( function(){ return '<a href="' + this.src + '"></a>'; });

or is it

$('img').wrap( function(){ return '<a href="' + $(this).attr('src') + '"></a>'; });

Anyways, fun times to be had, using jQuery to manipulate the DOM clientside ;)

2 Comments

I'm upvoting the other two for actually using PHP to fix the problem, but seriously, DOM element wrapping like this is pretty easy in jQuery, requires little effort on your part, and allows you to more tightly focus the areas to be "altered" if you suddenly decide that ... for instance, header images ... don't need to be selected. I'm not saying mine is necessarily the way to go, but just pointing out that there are some benefits to the awkward solution.
Related: jQuery

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.