Question

I have a string like this:

<p>This is a paragraph with an image <img src='/url-to-img.jpg' style='height:100px;width:30px;float:right;'></p>
<p>This is another paragraph with an image <img src='/url-to-img.jpg' style='margin:10px;height:100px;width:30px;float:left;'></p>

This string is from the database and the editor adds the image like that, unfortunately.

Now I want to edit this automatically using PHP to this:

<p>This is a paragraph with an image <img src='/url-to-img.jpg' style='height:100px;width:30px;float:right;' height=100 width=30 align='right'></p>
<p>This is another paragraph with an image <img src='/url-to-img.jpg' style='margin:10px;height:100px;width:30px;float:left;' height=100 width=30 align='left'></p>

I would like to get the height and width from the style and add them to the img tag.

Is this possible?

(This is so my image will show the alt text and not like a small square in Outlook. I want it to show as the full image)

Was it helpful?

Solution

You can use preg_match_all to get the width and height from style and then add these attributes using php str_replace. regular expression to match the width height would look like this: height:(.*?);width:(.*?);

$text = "<p>This is a paragraph with an image <img src='/url-to-img.jpg' style='height:100px;width:30px;float:right;'></p>
<p>This is another paragraph with an image <img src='/url-to-img.jpg' style='margin:10px;height:100px;width:30px;float:left;'></p>";

preg_match_all("/<img.*>/",$text,$out);
foreach($out as $t1)
{
    foreach($t1 as $img)
    {
        preg_match("/.*height:(.*?);width:(.*?);.*/",$img,$out2);
        $height = $out2[1];
        $width = $out2[2];
        $text = str_replace($out2[0],str_replace("<img","<img width='" . $width . "' height='" . $height . "'",$out2[0]),$text);
    }
}
echo $text;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top