2

How can I convert the following preg_replace to preg_replace_callback?

            $this->template = preg_replace ( "#\\[group=(.+?)\\](.*?)\\[/group\\]#ies", 
 "\$this->check_group('\\1', '\\2')", $this->template );

What I've tried:

        $this->template = preg_replace_callback( "#\\[not-group=(.+?)\\](.*?)\\[/not-group\\]#ies",
                function($this) {
                        return $this->check_group($this[1], $this[2], false);
                }
        , $this->template );

and the above preg_replace_callback gives me an empty result.

3 Answers 3

2

Don't use the \e modifier in your preg_replace_callback() call or php will throw the following warning and return nothing:

PHP Warning: preg_replace_callback(): Modifier /e cannot be used with replacement callback in /wherever/you/used/it.php on line xx

also, just a suggestion, don't use $this as your argument name in your callback function... that is just confusing.

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

Comments

2

In order to properly use '$this' in context you need to provide the use keyword for the anonymous function. Besides, $this is a special variable and its bad practice to use it directly as a function parameter. Also in your anonymous function, you're attempting to use $this as a variable for your matches, and I would replace $this in the function parameter with a more descriptive variable '$matches'. See if the following solves your problem.

    $this->template = preg_replace_callback( "#\\[not-group=(.+?)\\](.*?)\\[/not-group\\]#is",
            function($match) use ($this) {
                    return $this->check_group($match[1], $match[2], false);
            }
    , $this->template );

Comments

0

Because you are missing a semicolon ; there

return $this->check_group($this[1], $this[2], false);
                                             -------^ // Here

2 Comments

Can you update a test data and your expected output in the question ?
it seems that in php5.5 you can't use the e modifier. changed #ies to #isu and it's working now

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.