Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace all <img> parameters

I've upgraded a WYSIWYG editor from an old version to the newest. There is a difference to how image dimensions are saved. The old version of the editor used to add width and height parameters to the image tag. The new editor creates a style parameter and adds width and height as a style.

I have a preg_replace function that I use so that I can wrap an <a> tag around the <img>.

The current preg_replace doesn't work anymore since the new editor saves width and height in the style parameter.

Preg replace:

$Content = preg_replace('#<img(.*?)src="([^"]*/)?(([^"/]*)\.[^"]*)"([^>]*?)>((?!</a>))#', '<a rel="group" class="fancybox fancy" title="" href="$2$3"><img$1src="$2$3"></a>', $Content);

If good to know, the new editor stores images like this:

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

Whereas the old editor stored images like this:

<img src="" width="404" height="228" alt="" />

How can I refactor my preg_replace to copy the complete style element as well? Backwards-compatibility would be cool too.

Thanks for your time :)

like image 513
Gilly Avatar asked Jun 07 '13 11:06

Gilly


1 Answers

Try this:

$regex = '#<img([^>]*) src="([^"/]*/?[^".]*\.[^"]*)"([^>]*)>((?!</a>))#';
$replace = '<a rel="group" class="fancybox fancy" title="" href="$2"><img$1 src="$2"$3></a>';
$Content = preg_replace($regex, $replace, $Content);
like image 186
prothid Avatar answered Sep 27 '22 23:09

prothid