Webmaster Forum

Go Back   Webmaster Forum > Web Development > Coding Forum

Coding Forum Problems with your code? Discuss coding issues, including JavaScript, PHP & MySQL, HTML & CSS, Flash & ActionScript, and more.


Reply
 
Thread Tools Display Modes
Share |
  #1  
Old 02-19-2012, 11:36 PM
MarPlo's Avatar
MarPlo MarPlo is offline
Contributing Member
 
Join Date: 03-02-11
Posts: 94
iTrader: 0 / 0%
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?
 
Reply With Quote

Advertisement

Advertisement

  #2  
Old 02-20-2012, 04:12 AM
nemrod's Avatar
nemrod nemrod is offline
v7n Mentor
 
Join Date: 12-21-10
Location: Sweden
Posts: 463
iTrader: 0 / 0%
If you have full control of the variable content and the conditions are right (as they are in your example) then you can use eval:
PHP Code:
$t '12<-- AB_C -->';
$AB_C 'abc';
$str preg_replace('/\<-- ([A-Z_]+) --\>/''$$1'$t);
eval(
"\$str = \"$str\";");
echo 
$str
If you can instead put the stuff in an array it'll be a lot safer and more versatile:
PHP Code:
$t '12<-- AB_C -->';
$arr = array('<-- AB_C -->' => 'abc');
$str str_replace(array_keys($arr), $arr$t);
echo 
$str
 
Reply With Quote
  #3  
Old 02-20-2012, 06:47 AM
MarPlo's Avatar
MarPlo MarPlo is offline
Contributing Member
 
Join Date: 03-02-11
Posts: 94
iTrader: 0 / 0%
Thank you nemrod for the answer
The solution was the '/e' flag, which evaluates the replacement, solved the problem, and returns the results i want, using:
Code:
preg_replace('/\<-- ([A-Z_]+) --\>/e', "$$1", $t);
 
Reply With Quote
Go Back   Webmaster Forum > Web Development > Coding Forum

Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

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

Similar Threads
Thread Thread Starter Forum Replies Last Post
I need help grabbing the value of a variable with a dynamic prim3geek Coding Forum 2 04-25-2011 04:52 PM
preg_replace (I Guess?) Shaokan Coding Forum 8 07-22-2009 08:42 AM
PHP Dynamic Pages And Dynamic Meta Tags?? prasad_shejale SEO Forum 3 03-05-2008 10:42 AM
preg replace - replace links pairbrother Coding Forum 4 06-19-2007 12:19 PM
Trouble with using variable bytech Coding Forum 3 03-17-2005 11:57 PM


V7N Network
Get exposure! V7N I Love Photography V7N SEO Blog V7N Directory


All times are GMT -7. The time now is 08:52 AM.
Powered by vBulletin
Copyright 2000-2014 Jelsoft Enterprises Limited.
Copyright © 2003 - 2018 VIX-WomensForum LLC