Question

In this snippet I get the famous error preg_replace(): The /e modifier is deprecated, use preg_replace_callback in PHP 5.5.

    if (stripos($message, '[' . $tag . ']') !== false)
        $message = preg_replace('~\[' . $tag . ']((?>[^[]|\[(?!/?' . $tag . '])|(?R))+?)\[/' . $tag . ']~ie',
            "'[" . $tag . "]' . str_ireplace('[smg', '[smg', '$1') . '[/" . $tag . "]'", $message);

I was told I need to do this:

  • Add _callback in the function call,
  • remove the 'e' modifier,
  • and replace the replacement string with:

    function ($match) use ($tag) { return '[' . $tag . ']' . str_ireplace('[smg', '[smg', $match[1]) . '[/' . $tag . ']'; }
    

Can you help me with this? I really don't know how to do that...

Was it helpful?

Solution

You can use this:

$pattern = '~(\[' . $tag . '])((?>[^[]++|\[(?!/?+' . $tag . '])|(?R))*+)(\[/'
         . $tag . '])~i';
$message = preg_replace_callback($pattern,
                                 function ($m) {
                                     return $m[1]
                                          . str_ireplace('[smg', '[smg', $m[2])
                                          . $m[3];
                                 }, $message);

Notice: an other way (more readable) to write the same pattern with verbose mode and heredoc syntax:

$pattern = <<<EOF
~
(\[  $tag ])
( (?> [^[]++ | \[(?!/?+ $tag ]) | (?R) )*+ )
(\[/ $tag ])
~ix
EOF;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top