...

View Full Version : Replace with Dynamic variable in preg_replace



MarPlo
02-20-2012, 06:17 AM
Hi
I'm trying the following code:

$t = '12<-- AB_C -->';
$AB_C = 'abc';
echo preg_replace('/\<-- ([A-Z_]+) --\>/', "$$1", $t);
I want to get "12abc" , but it outputs: 12$AB_C , so, it not recognize the replacement as dynamic variable.
Is it any way to use the matched word in preg_replace() as a variable, or dynamic variable?

gvre
02-20-2012, 12:24 PM
You should add the "e (PREG_REPLACE_EVAL)" modifier to pattern

echo preg_replace('/\<-- ([A-Z_]+) --\>/e', "$$1", $t);
This code will throw a "Undefined variable" notice if the variable "$$1" has not been defined. You could replace the "$$1" with a function like the following to prevent these notices.


$t = '12<-- AB_C -->';
$data = array("AB_C" => "abc");
function r($v)
{
return isset($GLOBALS['data'][$v]) ? $GLOBALS['data'][$v] : "";
}

echo preg_replace('/<-- ([A-Z_]+) -->/e', "r('$1')", $t);

MarPlo
02-20-2012, 02:18 PM
Thank you gvre
The '/e' flag solved the problem.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum