Preg_replace all parameters <img>
I updated the WYSIWYG editor from the old version to the newest. There is a difference in how to save image sizes. The old version of the editor was 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 to wrap the <a> tag around <img> .
The current preg_replace no longer works, as the new editor saves the width and height in the style parameter.
Replace replacement:
$Content = preg_replace('#<img(.*?)src="([^"]*/)?(([^"/]*)\.[^"]*)"([^>]*?)>((?!</a>))#', '<a rel="group" class="fancybox fancy" title="" href="$2$3"><img$1src="$2$3"></a>', $Content); If you're interested, the new editor saves these images:
<img alt="" src="" style="" /> While the old editor stores images as follows:
<img src="" width="404" height="228" alt="" /> How can I reorganize my preg_replace to copy the complete style element? Backward compatibility will also be cool.
Thank you for your time:)
You can simplify the regex, note that you can use this solution if you expect the input to be correct, otherwise just use the html parser:
$string = 'Some text <img alt="bar" title="foo" src="http://example.com/example.jpg" style="width:200px;height:400px;" /> Some text'; $new_string = preg_replace('#<img.+?src="([^"]*)".*?/?>#i', '<a href="$1">$0</a>', $string); var_dump($new_string); Explanation:
<img: match<img.+?: match any one or more times (uneven)src=": matchsrc="([^"]*): match anything other than"zero or more times and group it".*?/?>: match"and then everything until/>or>imodifier: case insensitive
You can use <img.+?src\s*=\s*"([^"]*)".*?/?> , You never know, maybe there are spaces after and before = .
As Spudley said in his comment, you can seriously consider the DOM parser (Googleโs fast includes several options), especially if you donโt have control over how the editor adds images (although changing the editor to add links may be even easier, depending on which it is - I personally may not try to hack TinyMCE , but may consider it for wysihtml5 ).
Anyway, I'm distracted. With this approach, try to simplify the regular expression as much as possible. You just need to wrap it with the <a> tag, and not worry about the attributes themselves (as long as you keep them).
So try something like this (I tested this expression, but in Python, not in PHP, so YMMV):
preg_replace('<img(.*)src="([^ "]*)"([^>]*)>', '<a href="$2"><img$1src="$2"$3></a>', $whatever_your_string_is);