Search code examples
phppreg-replacepreg-replace-callback

preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead Array to string conversion


i use that function to convert URLs to active links

public function make_links_blank($text)
     {
        return  preg_replace(
   array(
   '/(?(?=<a[^>]*>.+<\/a>)
         (?:<a[^>]*>.+<\/a>)
         |
         ([^="\']?)((?:https?|ftp|bf2|):\/\/[^<> \n\r]+)
     )/iex',
   '/<a([^>]*)target="?[^"\']+"?/i',
   '/<a([^>]+)>/i',
   '/(^|\s)(www.[^<> \n\r]+)/iex',
   '/(([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@([A-Za-z0-9-]+)
   (\\.[A-Za-z0-9-]+)*)/iex'
   ),
 array(
   "stripslashes((strlen('\\2')>0?'\\1<a href=\"\\2\">\\2</a>\\3':'\\0'))",
   '<a\\1',
   '<a\\1 target="_blank" rel="nofollow">',
   "stripslashes((strlen('\\2')>0?'\\1<a        href=\"http://\\2\">\\2</a>\\3':'\\0'))",
   "stripslashes((strlen('\\2')>0?'<a href=\"mailto:\\0\">\\0</a>':'\\0'))"
         ),
        $text
   );
}

but i have an error

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


Solution

  • i used that code instead and it work well

        public function make_links_blank($text=''){ 
          $rexProtocol = '(https?://)?';
          $rexDomain   = '((?:[-a-zA-Z0-9]{1,63}\.)+[-a-zA-Z0-9]{2,63}|(?:[0-9]{1,3}\.){3}[0-9]{1,3})';
          $rexPort     = '(:[0-9]{1,5})?';
          $rexPath     = '(/[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]*?)?';
          $rexQuery    = '(\?[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
          $rexFragment = '(#[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';    
          return $text =  preg_replace_callback("&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFr agment(?=[?.!,;:\"]?(\s|$))&",
       function ($match)
      {
        $completeUrl = $match[1] ? $match[0] : "http://{$match[0]}";
        return '<a href="' . $completeUrl . '" rel="nofollow" target="_blank">'
        . $match[2] . $match[3] . $match[4] . '</a>';
     }
     , htmlspecialchars($text));
    }