Search code examples
phphtmlimagereplace

Add height attribute to <img> tags using getimagesize()


I want to alter my post_content string so that all <img> tags have a height attribute with a value derived from the image.

`preg_match_all doesn't suit my needs.

I've tried preg_filter(), but I can't call a function in the replacement parameter.

getimagesize(IMGURL)[1] is the height size pixel.

$2 is intented to be the img tag src URL in the replacement string.

preg_filter(
    '/<img(.+?)src="(.+?)"(.+?)>/i',
    "<img$1src=\"$2\"$3 height=\"" . getimagesize("{$2}")[1] . "\">",
    $row['post_content']
);

// <img src="/abc/a.jpg" height="">

preg_filter(
    '/<img(.+?)src="(.+?)"(.+?)>/i',
    "<img$1src=\"$2\"$3 height=\"".getimagesize(."{$2}".)[1]."\">",
    $row['post_content']
);

// PHP Parse error:  syntax error, unexpected '.' in /var/www/a/a.php line 22

My input string declaration:

$row['post_content'] = <<<HTML
<p>Hello my name is.</p>
<img src="sadsafdsd.jpg" alt><br>
<img src="sadsafdsfd.jpg" alt><br>
<img src="sadsgtjhsad.jpg" alt><br>
<img src="hgtsadsad.jpg" alt><br>
<img src="sadshtread.jpg" width="400" alt><br>
<img src="sadretsad.jpg" alt><br>
HTML;

Solution

  • You can use preg_replace_callback() instead.

    function setheight($matches){
        $img_prop = getimagesize($matches[2]);
        return '<img' . $matches[1] . 'src="'.$matches[2].'" '. $matches[3] . ' height="'.$img_prop[2].'">';
    }
    
    preg_replace_callback(
                "/<img(.+?)src=\"(.+?)\"(.+?)>/i",
                "setheight",
                $row['post_content']);