I'm reworking a WordPress plugin that I've made which specifies image dimensions that are missing width
and/or height
attributes.
As you can see in my current version on GitHub, I manually list all of the attributes for the <img>
tag (L38). However, if a user were to add custom attribute, it would get omitted since it's not listed in my $attributes
variable:
# Before
<img src=".png" class="img" custom-attr="value">
# After
<img src=".png" class="img" width="100" height="30">
Creating a simple test file, I was able to update the regex to store all attributes that are found in the <img>
tags. Yes, I'm aware of the recommendation to use DOMDocument, but it has caused more issues with WordPress in the past.
preg_match_all( '/(?:<img|(?<!^)\G)\h*([-\w]+)="([^"]+)"(?=.*?\/>)/', $content, $images );
In order to not fill up this post with too much code, I have the current working test file on my GitHub Gist here. You can also see the regex test here to verify.
Using var_dump( $images );
, this gives me the following output from my sample images (I added ...
at the end of each array to save space):
0 =>
array (size=19)
0 => string '<img src=".jpg?text=JPG"' (length=63)
1 => string ' alt="JPG"' (length=10)
2 => string '<img src=".gif?text=GIF"' (length=52)
...
1 =>
array (size=19)
0 => string 'src' (length=3)
1 => string 'alt' (length=3)
2 => string 'src' (length=3)
...
2 =>
array (size=19)
0 => string '.jpg?text=JPG' (length=52)
1 => string 'JPG' (length=3)
2 => string '.gif?text=GIF' (length=41)
...
My goal is to recreate the image tags with all of their attributes and values after the dimensions are calculated. From my tests, I've tried the following, but it hasn't given me the results I'm expecting:
foreach ( $images[1] as $attributes[1] => $value ) {
echo( '< img ' . $value . '="' . 'value' . '" ><br>' );
}