问题
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:
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]};
});
来源:https://stackoverflow.com/questions/30327522/cant-convert-preg-replace-with-modifier-e-to-preg-replace-callback