[PHP] 自动把URL转换为可以点击的超链接(自动加a标签) →→→→→进入此内容的聊天室

来自 , 2019-10-31, 写在 PHP, 查看 149 次.
URL http://www.code666.cn/view/b4944963
  1. function _make_url_clickable_cb($matches) {
  2.     $ret = '';
  3.     $url = $matches[2];
  4.  
  5.     if ( empty($url) )
  6.         return $matches[0];
  7.     // removed trailing [.,;:] from URL
  8.     if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
  9.         $ret = substr($url, -1);
  10.         $url = substr($url, 0, strlen($url)-1);
  11.     }
  12.     return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $ret;
  13. }
  14.  
  15. function _make_web_ftp_clickable_cb($matches) {
  16.     $ret = '';
  17.     $dest = $matches[2];
  18.     $dest = 'http://' . $dest;
  19.  
  20.     if ( empty($dest) )
  21.         return $matches[0];
  22.     // removed trailing [,;:] from URL
  23.     if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
  24.         $ret = substr($dest, -1);
  25.         $dest = substr($dest, 0, strlen($dest)-1);
  26.     }
  27.     return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;
  28. }
  29.  
  30. function _make_email_clickable_cb($matches) {
  31.     $email = $matches[2] . '@' . $matches[3];
  32.     return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
  33. }
  34.  
  35. function make_clickable($ret) {
  36.     $ret = ' ' . $ret;
  37.     // in testing, using arrays here was found to be faster
  38.     $ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_clickable_cb', $ret);
  39.     $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
  40.     $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
  41.  
  42.     // this one is not in an array because we need it to run last, for cleanup of accidental links within links
  43.     $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
  44.     $ret = trim($ret);
  45.     return $ret;
  46. }

回复 "自动把URL转换为可以点击的超链接(自动加a标签)"

这儿你可以回复上面这条便签

captcha