phpregexcallbackscopepreg-replace-callback

Add variable's value after each sequence of letters in a string using preg_replace_callback()


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

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