preg_replace img src, width, height stack overflow

389
November 29, 2017, at 04:48 AM

This's my codes:

$content = '<p><img src="http://localhost/contents/uploads/sdadaasa.jpg" width="1500" height="900"></p>';
$content = preg_replace('/<p><img.+src=[\'"]([^\'"]+)[\'"].*>/i', "<p class=\"the-image\"><img class=\"lazy-load\" src=\"$1\" width=\"\" height=\"\"/></p>", $content);
return $content;

My code is add a class for <p> tag and <img> tag.

Now i want to also get the width and height from $content because my code is removing the width and height attribute.

Answer 1

To parser HTML it's better to use any library as, for example, DomDocument

$content = '<p><img src="http://localhost/contents/uploads/sdadaasa.jpg" width="1500" height="900"></p>';
$dom = new DomDocument();
$dom->loadHTML($content);
$p = $dom->getElementsByTagName('p')->item(0);
$p->setAttribute('class', 'the-image');
$img = $p->getElementsByTagName('img')->item(0);
$img->setAttribute('class', 'lazy-load');
echo $dom->saveHTML($p); 
// <p class="the-image"><img src="http://localhost/contents/uploads/sdadaasa.jpg" width="1500" height="900" class="lazy-load"></p>
Rent Charter Buses Company
READ ALSO
statement if $i == 3 is not working

statement if $i == 3 is not working

I have 12 rows from mysql on 1 page and I have code:

159
How to select multiple rows from the same table only using one query?

How to select multiple rows from the same table only using one query?

I have one table from MySQL and I want to select some rows from this table without having to use lots of queries to find single rows

199
Date to Age Diff() errors in PHP

Date to Age Diff() errors in PHP

I'm falling between two errors while converting a date from datetimepicker to user's age

344
Positon pegman Google Maps FULLSCREEN wrongly positioned with Bootstrap

Positon pegman Google Maps FULLSCREEN wrongly positioned with Bootstrap

I'm having a problem with the Google Street View's pegman, it works normally in normal mode, but when I click on full screen and I'm going to try to put the pegman it's way above my mouse

198