1

I'm having a problem using a variable from preg_replace. Basically what I want to achieve is to look for some patterns in a text, and replace them by content. The replacement is done in a seperate function (retrieveValue() ). However I'm having difficulties passing the variable ('$1').

$types = array(
        array(
                '/\*#(.*?)#\*/',
                $this->retrieveValue($templateVars,'$1')    
             )
        );

    foreach ($types as $type) {
        $template = preg_replace($type[0], $type[1], $template);
    }  
0

1 Answer 1

4

The problem is that $this->retrieveValue($templateVars,'$1') is executed before you call preg_replace.

Solution: Have a look at preg_replace_callback.

I suggest you create a new method in your class:

public function _replace($matches) {
    return $this->retrieveValue($templateVars, $matches[1]);
}

and then can use:

preg_replace_callback('/\*#(.*?)#\*/', array($this, '_replace'), $template);

You can also make use of anonymous functions in PHP 5.3.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks this seems to be working, however is it possible to pass additional parameters to the _replace function (in addition to the $matches) ?
@user485659: No. But if you use PHP 5.3 you can use anonymous functions and closures.
@user485659: If you need to pass further parameters and you don't have PHP 5.3, have a look at create_function. Maybe you can somehow add the parameters differently.

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.