Search code examples
phppreg-replace-callback

preg_replace_callback gives multiple errors


I get an error on this line:

return preg_replace_callback("/([\\xF-\xC\xF]{1,1}[\\xBF-\\xBF]+)/e", _utf8_to_html("\\")', $data);

[cgi:error] [pid 8213] [client 151.56.154.134:58848] AH01215: PHP Warning: preg_replace_callback(): Requires argument 2, '_utf8_to_html("\1")', to be a valid callback in /home/informag/public_html/filename.php on line 951: /usr/local/cpanel/cgi-sys/ea-php54

Any idea to debug it?


Solution

  • besides the fact that there is a typo in the line (extra ' at the end of the second parameter) php actually expects the "callback" parameter to be either an anonymous function or string containing the name of the function to call. In your case, it would look something like:

    function _utf8_to_html() {
        // some logic...
    }
    
    preg_replace_callback("/([\\xF-\xC\xF]{1,1}[\\xBF-\\xBF]+)/e", '_utf8_to_html', $data);
    

    or

    $replacement = "\\"
    preg_replace_callback("/([\\xF-\xC\xF]{1,1}[\\xBF-\\xBF]+)/e", function() use ($replacement) {
        //some logic...
    }, $data);
    

    note that only the anonymous function solution will allow you to use more than one parameter in your callback function.