4

How can I pass a variable into the custom callback function of a preg_replace_callback() call?

For example, I'd like to use the variable $add within my callback function:

private function addToWord($add) {
    return preg_replace_callback(
        '/([a-z])+/i',
        function($word, $add) {
            return $word.$add;
        },
        $this->text
    );
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
R_User
  • 10,682
  • 25
  • 79
  • 120

2 Answers2

6

You can use use keyword here:

private function addToWord($add) {
    return preg_replace_callback(
        '/([a-z])+/i',
        function($word) use ($add) {
            return $word[1] . $add;
        },
        $this->text);
}
Community
  • 1
  • 1
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Using use is not needed for your task; neither is preg_replace_callback() or the capture group in your pattern.

Match your sequence of letters, then forget them with \K, then inject the $add value to the string at the position just after the sequence of letters.

private function addToWord($add)
{
    return preg_replace('/[a-z]+\K/i', $add, $this->text); 
}

Otherwise, this question is a duplicate of Callback function using variables calculated outside of it.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136