Can't convert preg_replace() with modifier /e to preg_replace_callback()

♀尐吖头ヾ 提交于 2019-12-12 21:30:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!