Thomas Williams Thomas Williams - 4 years ago 135
PHP Question

How to convert preg_replace e modifier to pref_replace_callback

I use a preg_replace for replacing words in templates

echo preg_replace('~%(\w+)%~e', '$obj->$1', $template);

$obj is an array of searches, and $template is the file I am searching and replacing. So I am replacing keywords like %REPLACE%.

Now I don't really understand how it works, and apparently the e modifier has just been deprecated so I think I have to use the pref_replace_callback instead. We are upgrading to php7 soon and so I must replace this line in my code.

Now I have already looked on stack overflow and found answers to other peoples similar problems, unfortunately the answers don't help with this particular pattern. I don't understand how this works let alone how to get preg_replace_callback working. I have tried reading up on preg_replace, but really I don't understand how it works.

So I how do I change the above code to preg_replace_callback?

PS. I have searched for tutorials on preg_replace_callback, but nothing that explains what I have to do.

This is not a duplicate of that other question. It is a completely different preg_replace. The answer to the other question does not answer my question, and I have not got the know how to work it out, as I am not very good with the preg_replace keyword.

Answer Source

Pretty sure this will work:

echo preg_replace_callback('~%(\w+)%~',
                           function($m) use($obj) {
                               return $obj->{$m[1]};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download