Jump to content

[SOLVED] Need help with advanced preg_match_all


haaglin

Recommended Posts

Hi.

 

This is getting to advanced for me, so i hope someone here can help me a bit. I dont even know if this can be done. Basicly i want to take all images on a page, replace the src with a php script that resizes the images, and also send the size of the images to the script;

 

Look at this example:

<img style="width: 460px; height: 406px" height="2336" src="http://www.domain.com/large_image.jpg" width="2336" alt="" />

 

This file is 8mb! I want to convert that line to this:

 

<img style="width: 460px; height: 406px" src="thumb.php?src=http://www.domain.com/large_image.jpg&w=460&h=406" alt="" />

 

So how can i get the src and the size from style tag of all images from a page (fetched from database) and end up with an array like this:

Array
(
[0] => Array 
(
	[src] 		=> http://www.domain.com/large_image.jpg
	[width] 	=> 460
	[height] 	=> 406
)
        [1] =>  Array 
(
	[src] 		=> http://www.domain.com/another_large_image.jpg
	[width] 	=> 400
	[height] 	=> 450
)
)

Care to share with everyone else?

Maybe there is a better way, but it works ;)

<?php
function replaceImages($doc) {
preg_match_all('/<img[^>]*>/im', $doc, $tags); 
$tags = $tags[0]; 
$mathes = array();
foreach($tags as $tag) {
	preg_match('/style="([^"]*)"/', $tag, $style);
	if(isset($style)){
		$style[1] = preg_replace('/[\s\ ]*/', "", $style[1]);  
		$style[1] = strtolower($style[1]);
		$style[1] = ";".$style[1].";";
		preg_match('/;width:([^;]*);/', $style[1], $widthMatch); 
		preg_match('/;height:([^;]*);/', $style[1], $heightMatch);
		if(isset($widthMatch[1]) && isset($heightMatch[1])){  
			$tempStr = substr($widthMatch[1], strlen($widthMatch[1])-2, 2);
			if($tempStr == 'px')
				$styleWidth = substr($widthMatch[1], 0, strlen($widthMatch[1])-2);
			$tempStr = "";  
			$tempStr = substr($heightMatch[1], strlen($heightMatch[1])-2, 2);
			if($tempStr == 'px')
				$styleHeight = substr($heightMatch[1], 0, strlen($heightMatch[1])-2); 
		}
		else {
			preg_match('/width="([0-9]+)"/', $tag, $w_match); 
			$styleWidth = $w_match[1];
			preg_match('/height="([0-9]+)"/', $tag, $h_match);
			$styleHeight = $h_match[1]; 
		} 
		preg_match('/src="([^"]*)"/', $tag, $srcstr);
		$temp = $srcstr[1]; 
		if(empty($styleHeight) && empty($styleWidth)) continue;
		$new = 'thumb.php?src='.urlencode($temp).'&w='.$styleWidth.'&h='.$styleHeight;
		$matches[$tag] = str_replace($temp,$new,$tag);

	}
}
if(!empty($matches)) {
	foreach($matches as $old => $new){
		$doc = str_replace($old,$new,$doc);
	}
}
return $doc;
}	
?>

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.