PHP解析链接/电子邮件 [英] Php parse links/emails

查看:72
本文介绍了PHP解析链接/电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一个简单的代码段可以转换任何形式的链接:

I am wondering if there is a simple snippet which converts links of any kind:

http://www.cnn.com to <a href="http://www.cnn.com">http://www.cnn.com</a>
cnn.com to <a href="http://www.cnn.com">cnn.com</a>
www.cnn.com to <a href="http://www.cnn.com">www.cnn.com</a>
abc@def.com to  to <a href="mailto:mailto:abc@def.com">mailto:abc@def.com</a>

我不想使用任何PHP5特定的库.

I do not want to use any PHP5 specific library.

谢谢您的时间.

更新,我已经将上面的文本更新为我想要将其转换为的文本.请注意,情况2和3的href标签和文本不同.

UPDATE I have updated the above text to what i want to convert it to. Please note that the href tag and the text are different for case 2 and 3.

UPDATE2 如何进行Gmail聊天?他们的域名非常聪明,仅适用于真实域名.例如a.ly有效,但a.cb不起作用.

UPDATE2 Hows does gmail chat do it? Theirs is pretty smart and works only for real domains names. e.g. a.ly works but a.cb does not work.

推荐答案

是, http://www.gidforums.com/t-1816.html

<?php
/**
   NAME        : autolink()
   VERSION     : 1.0
   AUTHOR      : J de Silva
   DESCRIPTION : returns VOID; handles converting
                 URLs into clickable links off a string.
   TYPE        : functions
   ======================================*/

function autolink( &$text, $target='_blank', $nofollow=true )
{
  // grab anything that looks like a URL...
  $urls  =  _autolink_find_URLS( $text );
  if( !empty($urls) ) // i.e. there were some URLS found in the text
  {
    array_walk( $urls, '_autolink_create_html_tags', array('target'=>$target, 'nofollow'=>$nofollow) );
    $text  =  strtr( $text, $urls );
  }
}

function _autolink_find_URLS( $text )
{
  // build the patterns
  $scheme         =       '(http:\/\/|https:\/\/)';
  $www            =       'www\.';
  $ip             =       '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
  $subdomain      =       '[-a-z0-9_]+\.';
  $name           =       '[a-z][-a-z0-9]+\.';
  $tld            =       '[a-z]+(\.[a-z]{2,2})?';
  $the_rest       =       '\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1}';            
  $pattern        =       "$scheme?(?(1)($ip|($subdomain)?$name$tld)|($www$name$tld))$the_rest";

  $pattern        =       '/'.$pattern.'/is';
  $c              =       preg_match_all( $pattern, $text, $m );
  unset( $text, $scheme, $www, $ip, $subdomain, $name, $tld, $the_rest, $pattern );
  if( $c )
  {
    return( array_flip($m[0]) );
  }
  return( array() );
}

function _autolink_create_html_tags( &$value, $key, $other=null )
{
  $target = $nofollow = null;
  if( is_array($other) )
  {
    $target      =  ( $other['target']   ? " target=\"$other[target]\"" : null );
    // see: http://www.google.com/googleblog/2005/01/preventing-comment-spam.html
    $nofollow    =  ( $other['nofollow'] ? ' rel="nofollow"'            : null );     
  }
  $value = "<a href=\"$key\"$target$nofollow>$key</a>";
} 

?>

这篇关于PHP解析链接/电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆