Eranda Jayarathne
Eranda Jayarathne

Reputation: 1

how to change img style width to attribute width in php

How can I go from this

<img style="width:200px; height:300px; ...

to this

<img width="200" height="300" ...

with PHP?

Upvotes: 0

Views: 757

Answers (3)

Antony Gibbs
Antony Gibbs

Reputation: 1497

An easy way can be not to touch to the html...

Find a way to target those images in your css and just adapt the display

div.myimages img {
    max-with:320px;
    height: auto!important;
}

Upvotes: 1

Tristup
Tristup

Reputation: 3663

If the style is already loaded with the img then the solutiona can be made with JQUERY :

$(function () {

                  width=$(this).css("width");
                  height=$(this).css("height");
                  $(this).attr("width",width);
                  $(this).attr("height",height);
 });

Hope it will serve your purposes.

Upvotes: 0

Casey Rule
Casey Rule

Reputation: 2085

It's gonna use some RegEx:

//use SimpleXMLElement to parse the attributes
$img = new SimpleXMLElement($imgStr);
$pattern = '~([a-z-]+)\s*:\s*([^;$]+)~si';

//convert the value of the style attribute into an associative array
if (preg_match_all($pattern, $img['style'], $match)) {
    $style[] = array_combine(
        array_map('strtolower', $match[1]),
        array_map(function($val) { return trim($val, '"\' '); }, $match[2])
    );  
}

// add the width and height attributes and get the new html
$img->addAttribute('width', $style[0]['width']);
$img->addAttribute('height', $style[0]['height']);
$newImgStr = $img->asXML();

// remove the width and height rules from the style attribute
$newImgStr = preg_replace('/width:([^;$]+);/', '', $newImgStr);
$newImgStr = preg_replace('/height:([^;$]+);/', '', $newImgStr);

Upvotes: 0

Related Questions