在PHP中将Eregi_replace转换为preg_replace

ale*_*rke -2 php regex

我需要帮助将eregi_replace转换为preg_replace(因为在PHP5中它已被折旧):

  function makeClickableLinks($text)
  {
  $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
                        '<a href="\\1">\\1</a>', $text);
  $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
                        '\\1<a href="http://\\2">\\2</a>', $text);
  $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
                        '<a href="mailto:\\1">\\1</a>', $text);
  return $text;
  }
Run Code Online (Sandbox Code Playgroud)

(它将文本链接和电子邮件转换为超链接,以便用户可以单击它们)

zom*_*bat 7

首先看一下手册中POSIX和PCRE表达式之间的差异列表.

如果你的表达式并不复杂,通常意味着只需在$pattern参数周围放置分隔符就可以逃脱,并切换到使用preg函数族.在你的情况下,你会这样做:

 function makeClickableLinks($text)
 {
 $text = preg_replace('/(((f|ht){1}tp:\/\/)[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)/i',
                       '<a href="\\1">\\1</a>', $text);
 $text = preg_replace('/([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)/i',
                       '\\1<a href="http://\\2">\\2</a>', $text);
 $text = preg_replace('/([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})/i',
                       '<a href="mailto:\\1">\\1</a>', $text);
 return $text;
 }
Run Code Online (Sandbox Code Playgroud)

请注意/模式周围的字符以及i分隔符后面的标记.我快速测试了这个,它适用于基本URL.你可能想要更彻底地测试它.