How to add image dimensions in an image being added via regex

Here is a piece of PHP code from a WordPress plugin that adds an image into the content by using preg_replace. The problem is that the added image has no dimensions specified and as this image is added multiple times on every page, it slows down page rendering (to a very small extent). Now, the question is:

How to add width = “1” and height= “1” into the final HTML of the image being added via the below mentioned PHP regex?

Read More
 // In case you want to change the placeholder image
        $placeholder_image = apply_filters( 'lazyload_images_placeholder_image', self::get_url( 'images/1x1.trans.gif' ) );


    // This is a pretty simple regex, but it works
        $content = preg_replace( '#<img([^>]+?)src=['"]?([^'"s>]+)['"]?([^>]*)>#', sprintf( '<img${1}src="%s" data-lazy-src="${2}"${3}><noscript><img${1}src="${2}"${3}></noscript>', $placeholder_image ), $content );
        return $content;

Any help would be appreciated, thanks!

Related posts

1 comment

  1. If none of them has dimensions set, You can simply add width="1" height="1" to img tag.

    Like this:

    $content = preg_replace( '#<img([^>]+?)src=['"]?([^'"s>]+)['"]?([^>]*?)(/)?>#', sprintf( '<img${1}src="%s" data-lazy-src="${2}"${3} width="1" height="1" /><noscript><img${1}src="${2}"${3}></noscript>', $placeholder_image ), $content );
    

    If added at the end of <img> tag it should’t interfer even when oryginal image would have it set already.

Comments are closed.