Replace with Dynamic variable in preg_replace

Status
Not open for further replies.

MarPlo

Active Member
29
2011
8
0
Hi
I'm trying the following code:
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?
 
2 comments
I am not really sure what you are trying to do here.

If you are trying to get the contents of the variable $AB_C to replace the string "<-- AB_C -->" in the example or what?

But if that is the case just use this:
PHP:
<?php
$t = '12<-- AB_C -->';
$AB_C = 'abc';
echo preg_replace('/\<-- ([A-Z_]+) --\>/', &$AB_C, $t);
?>
 
Hi,
I solved the problem using the "/e" flag, which makes the preg_replace() to evaluate the expresion before replacement.
Code:
preg_replace('/\<-- ([A-Z_]+) --\>/e', "$$1", $t);
 
Status
Not open for further replies.
Back
Top