0

I'm trying the following 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?

Edit:

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);

1 Answer 1

1

Could you use preg_replace_callback?

It's like preg_replace, but with a callback function that takes an array $matches where $matches[0] is the entire match, $matches[1] is the first capturing group, etc.

Perhaps something like (sorry, not tested):

 preg_replace_callback(
        '/\<-- ([A-Z_]+) --\>/',
        create_function(
            '$matches',
            'return $$matches[1];' // attempt to retrieve value of $AB_C
        ),
        $t
    );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.