2
votes

I am using preg_replace() to replace {#page} with the actual value of the variable $page. Of course I have a lot of {#variable}, not just {#page}.

For example:

$uri = "module/page/{#page}";
$page = 3;

//preg_replace that its working now
$uri_to_call = $uri_rule = preg_replace('/\{\#([A-Za-z_]+)\}/e', "$$1", $uri);

And I get the result

"module/page/3";

After update to PHP 5.4 i get the error:

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead

And I don't know how to rewrite the preg_replace() with preg_replace_callback().

I have try to follow the answer from SO Replace preg_replace() e modifier with preg_replace_callback

Like this:

public static function replace_vars($uri) { //$uri_rule = preg_replace('/\{\#([A-Za-z_]+)\}/e', "$$1", $uri);
        return preg_replace_callback('/{\#([A-Za-z_]+)\}/', 
           create_function ('$matches', 'return $$matches[1];'), $uri);

    }

But I also get a warning:

Notice: Undefined variable: page

Which is actually true because page variable it's not set runtime-created function.

Can anyone help me?

1
@Rizier123 i believe that this question after the edits its not duplicate - ntan
Your problem is, that in your anonymous function the variable variable is out of scope - Rizier123
@Rizier123 i know that and the variable $page and all others are dynamic variables.So there must me a way to replace "variable {#page}" with the value of $page.Thanks - ntan
So where are we now with this question ? - Rizier123

1 Answers

2
votes

Your problem is as you already know, that your variables are out of scope in your anonymous functions and since you don't know which one you will replace you can't pass them to the function, so you have to use the global keyword, e.g.

$uri = "module/page/{#page}";
$page = 3;

$uri_to_call = $uri_rule = preg_replace_callback("/\{\#([A-Za-z_]+)\}/", function($m){
    global ${$m[1]};
    return ${$m[1]};
});