Home » Php » html – Writing regular expression in PHP to wrap <img> with <a>

html – Writing regular expression in PHP to wrap <img> with <a>

Posted by: admin April 23, 2020 Leave a comment

Questions:

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.

How to&Answers:

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

handles all non-practical cases

alt text

Answer:

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

http://php.net/dom

http://php.net/domdocument.loadhtml

Answer:

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 😉