George
George

Reputation: 734

remove all CSS image style but keep html attributes (width and height)

i am storing html text in the database for example:

<p><img title="dasdasd" src="storage/posts/April2017/lKZCxXpP.jpg" alt="asdasd" width="100" height="100"/></p>

and then in another page i am displaying this text as html, consider it as a post body that need to be displayed with formatting.

the problem is that i am using a template that contain a lot of styling. in the style.css i have

img {  max-width: 100%;   height: auto;   width: 100%; }

its from the template styling and i cannot change this because it will mess up all my template.

the problem

the template styling is overriding the style of the image width ="100" height="100" that is stored with the html in the database, so i need the image to use the width and height that are provided by the creator of the post and stored in the database.

i already tried

height: unset;  width: unset;

but it will revert back the image to its original size not the one provided by the post creator.

is there anything i can do beside changing all the img style of themplate?

Upvotes: 2

Views: 1743

Answers (3)

WebiumMedia
WebiumMedia

Reputation: 260

Sorry reposting my answer for better formatting lol

So if you have more then one this would be the way:

<?php
$foo = '<p>
<img title="img 1" src="https://cdn-enterprise.discourse.org/sitepoint/community/user_avatar/www.sitepoint.com/paulob/45/44116_1.png" alt="asdasd" width="100" height="100"/>
<img title="img 2" src="https://cdn-enterprise.discourse.org/sitepoint/community/user_avatar/www.sitepoint.com/paulob/45/44116_1.png" alt="asdasd" width="200" height="200"/>
</p>';

$pattern = '/width="(\d+)"\s+height="(\d+)"/';
$replacement = 'style="width:$1;height:$2;"';
echo preg_replace($pattern, $replacement, $foo);
?>

Upvotes: 1

Shantosh Ramanathan
Shantosh Ramanathan

Reputation: 11

css always gives more priority to inline styles, so store the string in db like this

<p><img title="dasdasd" src="storage/posts/April2017/lKZCxXpP.jpg" alt="asdasd" style="width:100; height:100;" /></p>

and by the way simple way to retrieve images, good ideology u can even make simpler by just storing location of image and putting img tag using js

i hope this might help you

Upvotes: 1

WebiumMedia
WebiumMedia

Reputation: 260

You can extract the width and height of the HTML string and add a style attribute that equals that directly on the image. Add !important to it so that it becomes the default.

<?php

    $foo = '<p><img title="dasdasd" src="storage/posts/April2017/lKZCxXpP.jpg" alt="asdasd" width="100" height="100"/></p>';
    $parsedFoo = json_decode(json_encode(simplexml_load_string($foo)), true);
    $newFoo = str_replace('src=', 'style="height:'.$parsedFoo['@attributes']['height'].'!important;width:'.$parsedFoo['@attributes']['width'].'!important;" src=', $foo);

?>

Upvotes: 0

Related Questions