www.webdeveloper.com
Results 1 to 5 of 5

Thread: Replace with Dynamic variable in preg_replace

  1. #1
    Join Date
    Feb 2011
    Posts
    231

    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?

  2. #2
    Join Date
    Feb 2012
    Posts
    218
    Use replace() instead
    Code:
    	$t = '12<-- AB_C -->';
    	$AB_C = 'abc';
    	alert( $t.replace(/<-- AB_C -->/i, $AB_C) )

  3. #3
    Join Date
    Feb 2011
    Posts
    231
    Quote Originally Posted by hyperionXS View Post
    Use replace() instead
    Code:
    	$t = '12<-- AB_C -->';
    	$AB_C = 'abc';
    	alert( $t.replace(/<-- AB_C -->/i, $AB_C) )
    Hi
    alert() is not in PHP, your example is wrong.
    AB_C is not known, it is got with regexp.

  4. #4
    Join Date
    Feb 2012
    Posts
    218
    Oh, sorry, I thought it was JavaScript.
    For PHP use str_replace
    Code:
       $t = '12<-- AB_C -->';
       $AB_C = 'abc';
       echo str_replace('<-- AB_C -->', $AB_C, $t)

  5. #5
    Join Date
    Feb 2011
    Posts
    231
    For those who look for a solution to this problem, the '/e' flag, which evalates the replacement, solved the problem, and returns the results i want, using:
    Code:
    preg_replace('/\<-- ([A-Z_]+) --\>/e', "$$1", $t);
    Last edited by MarPlo; 02-20-2012 at 08:12 AM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles