2

I would like to check a string and convert all the substrings that could be potential links inside the original string like http://www.google.com, or www.google.com, replaced with <a href='http://www.google.com'>http://www.google.com</a> so that i can create real links from them.

How can i do this?

Alexander
  • 2,423
  • 4
  • 23
  • 17
  • 3
    possible duplicate of [How do I linkify urls in a string with php?](http://stackoverflow.com/questions/507436/how-do-i-linkify-urls-in-a-string-with-php) – alexn Jan 24 '11 at 10:15
  • @alexn: Not quite, as Alexander wants to also linkify URLs without `http://`. – Tim Pietzcker Jan 24 '11 at 11:45
  • @Tim Fair enough, then i recommend Alexander to look at the solution in this answer and modify it as needed http://stackoverflow.com/questions/1113840/php-remove-url-from-string – alexn Jan 24 '11 at 12:17

2 Answers2

1

you can create the HTML links by calling the following function in PHP:

$stringToCheck = 'http://www.google.com, or www.google.com';
$stringWithHTMLLinks = '';

$stringWithHTMLLinks = preg_replace('/\b((https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[A-Z0-9+&@#\/%=~_|]/si', '<a href="\0">\0</a>', $stringToCheck);
Broadhead
  • 66
  • 2
  • the h*ttp://www.google.com works fine but the www.google.com gives me http://localhost/migo2/www.google.com on localhost – Alexander Jan 26 '11 at 10:31
0

Use this regex provided on Daring Fireball to match an URL.

Ward Muylaert
  • 545
  • 4
  • 27
  • i'll be sure to check it out :) – Alexander Jan 25 '11 at 22:16
  • Here is the full version (IT IS LONG): `(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))` – a coder Feb 13 '13 at 19:19
  • Here is the shortened version (only matching http addresses): `(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))` – a coder Feb 13 '13 at 19:21
  • Also from Daring Fireball's page above: `Update: A few readers have asked what the licensing terms are for using this pattern in their own code. This pattern is free for anyone to use, no strings attached. Consider it public domain.` – a coder Feb 13 '13 at 19:22