Go Back   CodingForums.com > :: Server side development > PHP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-20-2012, 06:17 AM   PM User | #1
MarPlo
Regular Coder

 
Join Date: Mar 2011
Posts: 145
Thanks: 0
Thanked 20 Times in 20 Posts
MarPlo is an unknown quantity at this point
Replace with Dynamic variable in preg_replace

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?
__________________
MarPlo is offline   Reply With Quote
Old 02-20-2012, 12:24 PM   PM User | #2
gvre
Regular Coder

 
Join Date: May 2011
Posts: 212
Thanks: 1
Thanked 50 Times in 49 Posts
gvre is an unknown quantity at this point
You should add the "e (PREG_REPLACE_EVAL)" modifier to pattern
PHP Code:
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.

PHP Code:
$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); 
gvre is offline   Reply With Quote
Old 02-20-2012, 02:18 PM   PM User | #3
MarPlo
Regular Coder

 
Join Date: Mar 2011
Posts: 145
Thanks: 0
Thanked 20 Times in 20 Posts
MarPlo is an unknown quantity at this point
Thank you gvre
The '/e' flag solved the problem.
__________________
MarPlo is offline   Reply With Quote
Reply

Bookmarks

Tags
preg_replace

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 08:56 PM.


Advertisement
Log in to turn off these ads.