Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Mar 2011
    Posts
    148
    Thanks
    0
    Thanked 20 Times in 20 Posts

    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
    Regular Coder
    Join Date
    May 2011
    Posts
    241
    Thanks
    1
    Thanked 57 Times in 56 Posts
    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); 

  • #3
    Regular Coder
    Join Date
    Mar 2011
    Posts
    148
    Thanks
    0
    Thanked 20 Times in 20 Posts
    Thank you gvre
    The '/e' flag solved the problem.


  •  

    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
    •