0

There are a ton of questions on SO about converting preg_replace functions to preg_replace_callback, but none of them seem to address my specific issue.

After much searching, I have tried this but don't think it is complete:

OLD CODE:

$terms = preg_replace(
    "/\"(.*?)\"/e",
    "search_transform_term('\$1')",
    $terms
);

NEW CODE:

$terms = preg_replace_callback(
    "/\"(.*?)\"/",
    function ($m) {
        return "search_transform_term('\$1')";
    },
    $terms
);

This code is supposed to split multiple search terms whether separated by spaces or commas.

I am updating someone's old code and there are several more associated functions that will also need to be converted, so I am trying to learn how to do it.

The question is: "How do I properly convert this preg_replace to preg_replace_callback?"

I am providing my new code to show that I have been working on it before asking, and if I can wrap my brain around it I intend to do the rest myself.

Please be kind, this is all quite new to me.

shaun
  • 1,017
  • 11
  • 22
  • Just think about why would you have the variable `$m` in your anonymous function, when you don't use it?! So guess what's in this variable(`print_r($m);`) :) – Rizier123 Apr 21 '15 at 22:50
  • You are only returning a string, instead of calling the function … – CBroe Apr 21 '15 at 22:55
  • 1
    "There are a ton of questions ... but none of them seem to address my specific issue." This line is used a lot, but to make it make any sense, you need to explain what your specific issue is. The question "how do I convert something to `preg_replace_callback`?" is most definitely addressed by those other questions, so you need to ask something more specific. – IMSoP Apr 21 '15 at 22:56
  • Thanks for the link. I read several others and never saw that one. I could have been a little more specific, I guess, but since I am new I pretty much don't know what it is that I don't know. That link did answer my question, however. Now I understand a) how the preg_replace_callback function works, and b) that the anonymous function is not necessary, which was confusing since it is used in all of the examples I could find on PHP.net, etc. – Rod the Sun God Apr 22 '15 at 21:07

0 Answers0