Search code examples
phppreg-replacepreg-replace-callback

preg-replace image width, height and style


My image looks like this:

<img alt="" width="146" height="109" src="http://url.to/src.jpg" style="float:left" />

but i can't figure out how to bring it with preg_replace or preg_replace_callback to this:

<img alt="" src="http://url.to/src.jpg" style="width:146;height:109;float:left">

This works with height and width but I can't get the style-element "float:left" added

$html='<img alt="" width="146" height="109" src="http://url.to/src.jpg" style="float:left" />';
$pattern = ('/<img[^>]*width="(\d+)"\s+height="(\d+)">/');
preg_match($pattern, $html, $matches);
$style = "<img style=\"width:".$matches[1]."px; height:".$matches[2]."px;\"";
$html = preg_replace($pattern, $style, $html);

result of this will be

<img  alt="" style="width:146;height:109" src="http://url.to/src.jpg" style="float:left">

which didn't work because of the double style element


Solution

  • Try the following regular expression

    <?php
    
    $html='<img alt="" width="146" height="109" src="http://placehold.it/140x200" style="float:left" />';
    $pattern = '/(<img.*)width="(\d+)" height="(\d+)"(.*style=")(.*)" \/(>)/';
    $style = '$1$4width:$2px;height:$3px;$5';
    $html = preg_replace($pattern, $style, $html);
    echo $html; //view source of page to see the code change
    
    ?>
    

    Note the use of brackets '(' ')' to create groups matched that can be later referenced using $1 $2 etc go to regex101.com and try out the regular expression.

    Above code will result in following, except the last part, that shouldn't matter but you can modify it further.

    <img alt="" src="http://placehold.it/140x200" style="width:146;height:109;float:left" />