PHP – Convert URL into clickable link by Regular Expression

I want to convert the all URLs in a string into clickable links. I found a solution in StackOverflow but probably it only works in PHP 5.2 since it uses eregi_replace() which is deprecated in PHP 5.3. So use it with cares.

<?php
  function makeClickableLinks($text) {
    $text = html_entity_decode($text);
    $text = " ".$text;
    $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
            '<a href="\\1" target=_blank>\\1</a>', $text);
    $text = eregi_replace('(((f|ht){1}tps://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
            '<a href="\\1" target=_blank>\\1</a>', $text);
    $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
    '\\1<a href="http://\\2" target=_blank>\\2</a>', $text);
    $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
    '<a href="mailto:\\1" target=_blank>\\1</a>', $text);
    return $text;
  }
?>
<p><?php print makeClickableLinks("Go to http://eureka.ykyuen.info"); ?></p>
<p><?php print makeClickableLinks("Send email to abc@def.com"); ?></p>

 

Done =)

Reference: StackOverflow – Convert plain text URLs into HTML hyperlinks in PHP

Update @ 2012-03-05: TTime proposed a function without the deprecated eregi_replace() function (compatible with php 5.3). Please refer to his comment. Thanks TTime.

4 thoughts on “PHP – Convert URL into clickable link by Regular Expression”

  1. Here is the same function without the deprecated eregi_replace() function (compatible with php 5.3)

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

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.