5

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>

I do not want to use any PHP5 specific library.

Thank you for your time.

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 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.

Alec Smart
  • 94,115
  • 39
  • 120
  • 184

4 Answers4

5

yes , 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>";
} 

?>
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
  • doesnt work too well. if i type www.google.com its link remains as www.google.com instead of http://www.google.com. Also only google.com does not work. – Alec Smart Jun 24 '09 at 15:01
  • I think this does what the asker wants. Just not EXACTLY formatted the way he wants. He may have to modify this code a bit. – Travis Jun 24 '09 at 15:17
  • To match domains such as j.mp (another bitly URL shortener), just change the + in $name to a star(*), ie. $name = '[a-z][-a-z0-9]*\.'; – Jrgns Jan 22 '11 at 07:52
  • I prefer being minimalistic if PHP functions are available: [parse_url()](http://php.net/manual/en/function.parse-url.php) does the most essential of above what "function _autolink_find_URLS()" does. – Leo Feb 17 '13 at 20:09
2

Try this out. (for links not email)

$newTweet = preg_replace('!http://([a-zA-Z0-9./-]+[a-zA-Z0-9/-])!i', '<a href="\\0" target="_blank">\\0</a>', $tweet->text);
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
0

I know is 5 years late, however I needed a similar solution and the best answer I got was from the user - erwan-dupeux-maire

Answer

I write this function. It replaces all the links in a string. Links can be in the following formats :

The second argument is the target for the link ('_blank', '_top'... can be set to false). Hope it helps...

public static function makeLinks($str, $target='_blank')
{
    if ($target)
    {
        $target = ' target="'.$target.'"';
    }
    else
    {
        $target = '';
    }
    // find and replace link
    $str = preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1" '.$target.'>$1</a>', $str);
    // add "http://" if not set
    $str = preg_replace('/<a\s[^>]*href\s*=\s*"((?!https?:\/\/)[^"]*)"[^>]*>/i', '<a href="http://$1" '.$target.'>', $str);
    return $str;
}
Community
  • 1
  • 1
Oliver Bayes-Shelton
  • 6,135
  • 11
  • 52
  • 88
-1

Here's the email snippet:

$email = "abc@def.com";

$pos = strrpos($email, "@");
if (!$pos === false) {
    // This is an email address!
    $email .= "mailto:" . $email;
}

What exactly are you looking to do with the links? strip the www or http? or add http://www to any link if required?

EvilChookie
  • 563
  • 3
  • 14
  • 31