Hiya,
I've been having a bit of a problem trying to get some code working. I'm trying to get preg_replace to replace some parameters in an HTML template file with PHP variables. Doing this is easy enough when I just code up my PHP with normal functions, but as soon as I try to do it within an object it stops working (needless to say this is how I would like to do it). I’ve simplified the code I’m working on down into the two snippets below, now I might just be missing something completely obvious (I've only been using PHP a little while), but could someone explain why out of the following two pieces of code only the first replaces {foo} with BAR ...
The 'normal' just plain old PHP version:
<?php
$input = "the string i want parsed through to replace {foo} okay?";
$foo = "BAR";
function parse($data)
{
$data = preg_replace("/{(\w+)}/ie", "replace_param($1);", $data);
return $data;
}
function replace_param($param)
{
global $input, $foo;
return $$param;
}
$output = parse( $input );
echo( "<tt>before =<b> $input </b>\n<br>\n after =<b> $output </b></tt>" );
?>
The slightly more complicated 'object' PHP (which doesn't work as I expected) version:
<?php
$input = "the string i want parsed through to replace {foo} okay?";
$foo = "BAR";
class someclass {
function parse($data)
{
$data = preg_replace("/\{(\w+)\}/ie", "$this->replace_param($1);", $data);
return $data;
}
function replace_param($param)
{
global $input, $foo;
return $$param;
}
}
$newobj = new someclass;
$output = $newobj->parse( $input );
echo( "<tt>before =<b> $input </b>\n<br>\n after =<b> $output </b></tt>" );
?>
When I run the first code snipet I get the following:
before = the string i want parsed through to replace {foo} okay?
after = the string i want parsed through to replace BAR okay?
And when I run the second I get:
before = the string i want parsed through to replace {foo} okay?
after = the string i want parsed through to replace foo okay?
As you can see the {foo} wasn't replaced by the variable $foo ('BAR') as I would have expected. I've tried quite a few iterations of this code and can't get it doing what I want (I have tried putting the variables within the class and doing the replacement like this $this->{$param} ). If anyone has any ideas about this I'd appreciate them.
Thanks
ChilliBear