Intriguing preg_replace(); question. Embedding a function with a backreference

From: NorfolkMustard (nospam_at_ntlworld.com)
Date: 02/27/05


Date: Sun, 27 Feb 2005 01:04:32 GMT


[img=WxH]http://url.com/img.jpg[/img]

That will be familiar to a lot of us as 'BBCode' used in a lot of online
forums as a simpler form of the <img height='H' width='W' /> tag

Now, I want to make it easier for my members to keep to reasonable sizes of
images by automating the WxH calculation

I'm trying preg_replace(); for this. Here's where I'm upto. It seems to be
falling over when trying to put a backreference, in a function, in a
preg_replace();

-------------

<?
function imageResize($imgurl) {
 $imgbits = getimagesize($imgurl);
 if ($imgbits[0] > $imgbits[1]) {
  $percentage = (340 / $imgbits[0]);
 } else {
  $percentage = (340 / $imgbits[1]);
 }

 //gets the new value and applies the percentage, then rounds the value
 $width = round($imgbits[0] * $percentage);
 $height = round($imgbits[1] * $percentage);

 //returns the new sizes in bbcode image tag format

 return "[img=".$width."x".$height."]".$imgurl."[/img]";
} //end function

//the input text we want to update with a resized [img=HxW]
$subject = "hello, how about this beauty
then:[img]http://forums.seloc.org/images/xpsilver/new.gif[/img]42 karat
plonker";

//some debug code for my sanity
if (preg_match('/\\[img\\](.*?)\\[\/img\\]/', $subject, $regs)) {
 $result = $regs[1];
} else {
 $result = "nope";
}
print_r($result);
$stuff = getimagesize($result);

echo "<br /><br />";
print_r($stuff);

//the code.
$wow = preg_replace('/\\[img\\](.*?)\\[\/img\\]/', imageResize('$1'),
$subject);
echo "<br /><br />";
print_r($wow);

?>

-----------------