Vaibs_Cool
Vaibs_Cool

Reputation: 6156

need a regular expression to get width and height from image url in php

My image class

$temp=<img class="alignnone wp-image-6" alt="2166105529_70dd50ef4b_n" src="http://192.168.1.12/wordpress/wp-content/uploads/2013/03/2166105529_70dd50ef4b_n-300x175.jpg" width="180" height="105">

I want to grab width and height from the url i.e. width="180" and height="105"

I had already got the src part of that using

preg_replace('/<img\s.*?\bsrc="(.*?)".*?>/si', $temp, $matches);

$matches= it contains extracted src like this

http://192.168.1.12/wordpress/wp-content/uploads/2013/03/2166105529_70dd50ef4b_n-300x175.jpg

Now how to extract width and height using regex or any other method also accepted??

Upvotes: 0

Views: 2183

Answers (3)

chh
chh

Reputation: 593

I prefer to use PHP's DOM extension for this, because it's more reliable and knows how to parse HTML correctly, and knows something about character sets.

<?php

$temp='<img class="alignnone wp-image-6" alt="2166105529_70dd50ef4b_n" src="http://192.168.1.12/wordpress/wp-content/uploads/2013/03/2166105529_70dd50ef4b_n-300x175.jpg" width="180" height="105">';

$dom = new \DomDocument;
$dom->loadHTML($temp);

$img = $dom->getElementsByTagName('img')->item(0);

// Note: Values are returned as strings, not as numbers
$src = $img->getAttribute('src');
preg_match('/(.+)-([0-9]+)x([0-9]+)\.jpg$/', $src, $matches);

$width = $matches[2];
$height = $matches[3];

Upvotes: 4

dave
dave

Reputation: 64657

You can just do

list($height, $width) = explode("x",substr(strrchr( $url , "-" ),1,-4));

And if I misunderstood and you need to get it from the attributes, not the actual url of the image, then

$url= '<img class="alignnone wp-image-6" alt="2166105529_70dd50ef4b_n" src="http://192.168.1.12/wordpress/wp-content/uploads/2013/03/2166105529_70dd50ef4b_n-300x175.jpg" width="180" height="105">';

echo substr(strstr( $url , "width" ),0,-1);

Will echo

width="180" height="105"

Upvotes: 0

S.Visser
S.Visser

Reputation: 4725

Using the dom class in php is a better way. Much easier to use. Example: http://sandbox.onlinephpfunctions.com/code/c6d89fc6e0803ac38a3bc1ea9c61e081c1b71f08

$dom = new DOMDocument();
$dom->loadHTML('<img class="alignnone wp-image-6" alt="2166105529_70dd50ef4b_n" src="http://192.168.1.12/wordpress/wp-content/uploads/2013/03/2166105529_70dd50ef4b_n-300x175.jpg" width="180" height="105">');

$img = $dom->getElementsByTagName('img');

$src= $img->item(0)->getAttribute('src'); 
$width= $img->item(0)->getAttribute('width'); 
$height= $img->item(0)->getAttribute('height'); 

echo $src ."<br/>";
echo $width."<br/>";;
echo $height."<br/>";;

Upvotes: 4

Related Questions