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.

Jonah
  • 9,991
  • 5
  • 45
  • 79
gio
  • 375
  • 3
  • 8
  • 1
    So you are converting `` into ``? – Ming-Tang Dec 16 '10 at 02:00
  • 7
    Obligatory: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 :) (In your case it's probably manageable, but Cthulu still applies.) – deceze Dec 16 '10 at 02:00

3 Answers3

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

Trufa
  • 39,971
  • 43
  • 126
  • 190
Ming-Tang
  • 17,410
  • 8
  • 38
  • 76
11

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

http://php.net/dom

http://php.net/domdocument.loadhtml

Jonah
  • 9,991
  • 5
  • 45
  • 79
7

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 ;)

jcolebrand
  • 15,889
  • 12
  • 75
  • 121
  • 3
    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. – jcolebrand Dec 16 '10 at 02:17
  • Related: *[jQuery](http://meta.stackexchange.com/questions/19478/the-many-memes-of-meta/19492#19492)* – Peter Mortensen Jul 22 '16 at 21:07