Search code examples
phppreg-replacepreg-replace-callback

Deprecated: preg_replace(): The /e modifier is deprecated error


Hi I'm working on wordpress theme and write a custom widget it's working properly. But when I make wp_debug = true it's giving this error

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in ....

Here is the my preg_replace code

$status = preg_replace("/((http:\/\/|https:\/\/)[^ )]+)/e", "'<a href=\"$1\" title=\"$1\" $target >'. ((strlen('$1')>=$linkMaxLen ? substr('$1',0,$linkMaxLen).'...':'$1')).'</a>'", $status);

I'm trying change it like this

$status = preg_replace_callback(
                "/((http:\/\/|https:\/\/)[^ )]+)/e",
                function($matches) {
                    return "'<a href=\"$1\" title=\"$1\" $target >'. ((strlen('$1')>=$linkMaxLen ? substr('$1',0,$linkMaxLen).'...':'$1')).'</a>'";
                },
                $status
            );

But it's not working. How can I fix this?


Solution

  • In the callback, substitute $1 by $matches[1]:

    function($matches) {
        return "'<a href=\"$matches[1]\" title=\"$matches[1]\" $target >'
            . (
                ( strlen($matches[1]) >= $linkMaxLen ? 
                      ? substr(matches[1], 0, $linkMaxLen).'...'
                      : matches[1]
                )
              )
            .'</a>'"
    },