Utku Dalmaz
Utku Dalmaz

Reputation: 10172

creating hyperlinks from plain text

I use this code to make plain texts hyperlinks.

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

But it doesnt work when text is www.domain.com or domain.com or subdomain.domain.com

How can i make it work with them ?

Thanks

Upvotes: 1

Views: 393

Answers (2)

mario
mario

Reputation: 145482

There are heaps of duplicates of this question, which is the very fact that makes it more difficult to find the right one. Accept this list instead:

But since you already have something that you think works for you, there would be the option to just add the edge case. Finding sub.domain.com is not easy and likely leads to false positives. But converting them to http:// urls so the other rules pick them up would be possible by applying this first:

$text = preg_replace('#(?<!://)w+\.\w+\.(com|net|org|\w\w)\b\S*#', "http://$0", $text);
$text = preg_replace('#(?<!://)www\.\S+#', "http://$0", $text);

Instead of \S you could use your lengthy character class.

Upvotes: 1

Related Questions