1

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.

Thomas Williams
  • 1,528
  • 1
  • 18
  • 37

1 Answers1

1

Pretty sure this will work:

echo preg_replace_callback('~%(\w+)%~',
                           function($m) use($obj) {
                               return $obj->{$m[1]};
                           },
                           $template);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • I just tried this, and it is not giving me anything back at all. It looks like it should work, but doesn't seem to – Thomas Williams Feb 06 '17 at 21:20
  • I worked it out. I used your solution, but I removed the e modifier. If you edit your answer I will upvote you. – Thomas Williams Feb 06 '17 at 21:29
  • Well damn, that was bone-headed of me. – AbraCadaver Feb 06 '17 at 21:39
  • It took me a little time to work it out. preg_replace has always been a grey area for me. I have tried reading up on it, but find it very hard to understand. At least now I know I am safe when we upgrade to php7. I am going to try and understand it more, but it is hard to learn when people are rushing you to get a webpage finished. Thanks – Thomas Williams Feb 06 '17 at 21:52