Question

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
    );
}
Was it helpful?

Solution

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);
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top