1

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://<a href="http://www.chemica.ru">www.chemica.ru</a>">http://<a href="http://www.chemica.ru">www.chemica.ru</a></a>

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">\\1</a>', $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; 
}
Denis Bobrovnikov
  • 634
  • 3
  • 10
  • 19
  • 3
    FYI, eregi_* functions are deprecated. You should switch to preg_replace at some point in the near future. – webbiedave Sep 21 '10 at 17:18
  • PCRE allows for more advanced regex features than POSIX, as well. – Daniel Vandersluis Sep 21 '10 at 18:01
  • possible duplicate of [How to extract http links from a paragraph and store them in a array on php](http://stackoverflow.com/questions/6861324/how-to-extract-http-links-from-a-paragraph-and-store-them-in-a-array-on-php) – hakre Jan 28 '12 at 20:16

3 Answers3

4

just write to your view's page (you dont need any library or helper function) :

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

echo $link;
Flexo
  • 87,323
  • 22
  • 191
  • 272
andy
  • 41
  • 1
  • This code works up to PHP7.2.31 but fails from 7.3 onwards ("preg_replace(): Compilation failed: invalid range in character class at offset 14"). See http://sandbox.onlinephpfunctions.com/code/81dd9ff6b356368fa3484c7ea897eebf261d2516 – user1432181 May 03 '21 at 10:55
2

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@:%_\+.~#?&/=]+) 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">\1</a>', $text);

should work.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

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
  • 41,517
  • 32
  • 98
  • 131