Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing regular expression in PHP to wrap <img> with <a> [duplicate]

Tags:

html

regex

php

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.

like image 732
gio Avatar asked Dec 16 '10 01:12

gio


2 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

like image 144
Ming-Tang Avatar answered Sep 26 '22 23:09

Ming-Tang


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

http://php.net/dom

http://php.net/domdocument.loadhtml

like image 29
Jonah Avatar answered Sep 25 '22 23:09

Jonah