Search code examples
cakephppreg-replace-callback

cakePHP v2, TextHelper::autoLinkUrls, preg_replace_callback(), Error: Requires argument 2


Has anybody had trouble with using the autoLinkUrls function in cakePHP v2.0?

It's giving me this error:

Warning (2): preg_replace_callback() [function.preg-replace-callback]: Requires argument 2, 'View::_linkBareUrl', to be a valid callback [CORE\Cake\View\Helper\TextHelper.php, line 128]

Solution

  • Don't call none-static methods statically

    The code for the function you're referring to is:

    public function autoLinkUrls($text, $htmlOptions = array()) {
        $this->_linkOptions = $htmlOptions;
        $text = preg_replace_callback(
            '#(?<!href="|src="|">)((?:https?|ftp|nntp)://[^\s<>()]+)#i',
            array(&$this, '_linkBareUrl'),
            $text
        );
        return preg_replace_callback(
            '#(?<!href="|">)(?<!http://|https://|ftp://|nntp://)(www\.[^\n\%\ <]+[^<\n\%\,\.\ <])(?<!\))#i',
            array(&$this, '_linkUrls'),
            $text
        );
    }
    

    It's not a static method but based upon the error message - $this is a view instance. That means you're probably calling it statically i.e.:

    echo TextHelper::autoLinkUrls($foo);
    

    This is wrong, don't do that - instead use it as designed:

    echo $this->Text->autoLinkUrls($foo);
    

    Your version of cake is old

    While it's not relevant to the problem at hand, 2.0.0 is two years old. There have been 6 patch releases since then and it would be wise to update to the lastest of them (2.0.6 at the time of writing. Bug-fix/patch release have no functional changes at all). Upgrading to a more recent minor releas (2.1.x, 2.2.x, 2.3.x) will introduce new functionality but also the need to review your application and possibly adapt to introduced/removed api/functional changes.