I have the following code, but it replaces every img tag with just: <img /> I need all of the attributes included in the replacement.
For example, this: <img src="images/myimg.gif" alt="">
Is supposed to turn into this: <img src="images/myimg.gif" alt="" />
Here is my current non-working code: $html = preg_replace("/<img[^>]+\>/i", "<img $1 />", $html);
Add the brackets around the attributes in the regex, then you can use $1 in in the replacer:
$html = preg_replace("/<img([^>]+)\>/i", "<img $1 />", $html);
Also see this example.
If you want to use $1
you need at first to store something into it. this is done by a capturing group, meaning simply put brackets around the pattern you want to reuse.
$html = preg_replace("/<img([^>]+)\>/i", "<img $1 />", $html);
There are several online tools where you can test your regexes, see your regex e.g. here on RegExr
You can find more about groups here on regular-expressions.info
$html = preg_replace("@(<img.*?)(?<!/)>@i", "$1/>", $html);
This regex may work for you, but if applied repeatedly, it will insert the /
again and again, resulting in <img ... / / / / />
and so on:
$html = preg_replace("/<img([^>]+)\>/is", "<img \1 />", $html);
To avoid this, you can use negative lookbehind (?<!\/)
:
$html = preg_replace("/<img([^>]+)(?<!\/)\>/is", "<img \1 />", $html);
it matches only image tags, that are not closed with a />