Replace with Dynamic variable in preg_replace

Discussion in 'PHP' started by MarPlo, Feb 19, 2012.

  1. #1
    Hi
    I'm trying the following code:
    $t = '12<-- AB_C -->';
    $AB_C = 'abc';
    echo preg_replace('/\<-- ([A-Z_]+) --\>/', "$$1", $t);
    Code (markup):
    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, Feb 19, 2012 IP
  2. MarPlo

    MarPlo Member

    Messages:
    97
    Likes Received:
    2
    Best Answers:
    2
    Trophy Points:
    48
    #2
    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:
    preg_replace('/\<-- ([A-Z_]+) --\>/e', "$$1", $t);
    Code (markup):
     
    MarPlo, Feb 20, 2012 IP
  3. Lee Stevens

    Lee Stevens Active Member

    Messages:
    148
    Likes Received:
    3
    Best Answers:
    2
    Trophy Points:
    68
    #3
    Thanks, i code regular in PHP and didn't no that! Thanks for letting us no after you found a solution!
     
    Lee Stevens, Feb 22, 2012 IP
  4. ogah

    ogah Member

    Messages:
    60
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    36
    #4
    this is a similar
    
    echo str_replace('<-- AB_C -->', $AB_C, $t);
    
    Code (markup):
     
    ogah, Mar 5, 2012 IP