View Full Version : Replace with Dynamic variable in preg_replace

02-20-2012, 07:17 AM
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?

02-20-2012, 01: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);

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