views:

41

answers:

2

I have got a function that converts strings like 'www.example.com' and 'http://example.com' in hyperlinks. It also deals with subdomains e.g. 'http://sub.example.com'.

But it fails with this one - http://www.example.com' and outputs the following

<a href="http://&lt;a href="http://www.chemica.ru"&gt;www.chemica.ru&lt;/a&gt;"&gt;http://&lt;a href="http://www.chemica.ru"&gt;www.chemica.ru&lt;/a&gt;&lt;/a&gt;

Please, can anyone help? The problem is that both 'http://' and 'www.' are together and both have different ways of converting.

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

You might want to read this blog post by Jan Goyvaerts for some ideas on how to find URLs in text.

To solve your immediate problem, you could add a negative lookbehind to your second regex: (?<!http://)(www.[-a-zA-Z0-9@:%_\+.~#?&amp;/=]+) ensures that www... will only be matched if it is not preceded by http://.

However, ereg functions are deprecated and don't support lookaround, so you'll need to use preg_replace().

$text = preg_replace('/(?<!http:\/\/)(www.[-a-zA-Z0-9@:%_\+.~#?&\/=]+)/i', '<a href="http://\1"&gt;\1&lt;/a&gt;', $text);

should work.

Tim Pietzcker
A: 

For both 'http://' and 'www.' together, you can do something like this:

$text = "http://www.example.com is a nice site";
$link = preg_replace("/([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i","<a target=\"_blank\" href=\"$1\">$1</a>", $text);
echo $link;

Works for URLs starts with http://

NAVEED