Q . How to set width height of any image tag which has not these attributes ?

Mike Tyson. asked, May 11 ' 2018
<html>
	<head></head>
	<body>
		This is a body
		
		Image 1.
		<img src="http://www.codeman.in/assets/image/logos/new-codeman.png" width="" height="" />
		
		Image 2.
		<img src="http://www.codeman.in/assets/image/logos/new-codeman.png" width=""/>
		
		Image 3.
		<img src="http://www.codeman.in/assets/image/logos/new-codeman.png" />
	</body>
</html>

I have to add width height if it doesnot exist or empty.

  • PHP
  • DOMDocument
  • image-width
  • image-height

2 Answers

Try This :

$content = 'html content here';

$dom = new DOMDocument;
$dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$nodes = $dom->getElementsByTagName('amp-img');
foreach ($nodes as $node) {
	if (!$node->hasAttribute('width') || empty(trim($node->getAttribute('width')))) {
		$node->setAttribute('width', 800);
	}
	if (!$node->hasAttribute('height') || empty(trim($node->getAttribute('height')))) {
		$node->setAttribute('height', 419);
	}
}
$content = html_entity_decode($dom->saveHTML());


//Converting the character encoding of string $html, to UTF-8 and then load it to the DOM, using 2 libxml predefined constants (LIBXML_HTML_NOIMPLIED & LIBXML_HTML_NODEFDTD).

//The first one sets HTML_PARSE_NOIMPLIED flag, which turns off the automatic adding of implied html/body... elements (which is only avilable as of PHP 5.4.0).

//The second one sets HTML_PARSE_NODEFDTD flag, which prevents a default doctype being added when one is not found. using these constants help you manage your parsing in a more flexible manner.

 

Try with Regex.


$newContent = setImageWidthHeight(<Your content>, <width to be set>, <height to be set>);

function setImageWidthHeight($content, $width, $height) {
    preg_match_all('#<img.*?\/>#is', $content, $matches);

    foreach ($matches[0] as $key => $img) {

        preg_match('#<img.*?(width)=[\'\"]?([0-9]+)?[\'\"]?.*?\/>#is', $img, $widthMatches);
        if (empty($widthMatches[1]) || empty($widthMatches[2])) {
            $newWidthImg = preg_replace('#width=?[\'\"]?([0-9]+)?[\'\"]?#', '', $img);
            $newWidthImg = preg_replace('#<img(.*?)\/>#', '<img$1 width="' . $width . '" />', $newWidthImg);
            $content = str_replace($img, $newWidthImg, $content);
        }

        preg_match('#<img.*?(height)=[\'\"]?([0-9]+)?[\'\"]?.*?\/>#is', $img, $heightMatches);
        if (empty($heightMatches[1]) || empty($heightMatches[2])) {

            $newImage = !empty($newWidthImg) ? $newWidthImg : $img;
            $newHeightImg = preg_replace('#height=?[\'\"]?([0-9]+)?[\'\"]?#', '', $newImage);
            $newHeightImg = preg_replace('#<img(.*?)\/>#', '<img$1 height="' . $height . '" />', $newHeightImg);
            $content = str_replace($newImage, $newHeightImg, $content);
        }
    }

    return $content;
}

 

Leave a Ansewer