php实现使用正则将文本中的网址转换成链接标签

本文给大家分享一段php中使用正则表达式将网址转换成A链接的函数代码,十分简洁实用,这里推荐给大家,代码如下:

  1. function text2links($str='') {
  2. if($str=='' or !preg_match('/(http|www\.|@)/i', $str)) { return $str; }
  3. $lines = explode("\n", $str); $new_text = '';
  4. while (list($k,$l) = each($lines)) {
  5. // replace links:
  6. $l = preg_replace("/([ \t]|^)www\./i", "\\1http://www.", $l);
  7. $l = preg_replace("/([ \t]|^)ftp\./i", "\\1ftp://ftp.", $l);
  8. $l = preg_replace("/(http:\/\/[^ )\r\n!]+)/i",
  9. "<a href=\"\\1\">\\1</a>", $l);
  10. $l = preg_replace("/(https:\/\/[^ )\r\n!]+)/i",
  11. "<a href=\"\\1\">\\1</a>", $l);
  12. $l = preg_replace("/(ftp:\/\/[^ )\r\n!]+)/i",
  13. "<a href=\"\\1\">\\1</a>", $l);
  14. $l = preg_replace(
  15. "/([-a-z0-9_]+(\.[_a-z0-9-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)+))/i",
  16. "<a href=\"mailto:\\1\">\\1</a>", $l);
  17. $new_text .= $l."\n";
  18. }
  19. return $new_text;
  20. }