Possible Duplicate:
Replace URLs in text with HTML links
I'm writing some code to convert plain-text links to HyperText links in PHP. I'm using a regular expression (of which I know almost nothing) and I'm coming up against some problems:
- I don't know how to conditionally include/exclude an item in the expression
- I don't know how to include URL parameters in my expression
- I don't know much about RegEx!
This is the code I've written:
function text2link($text)
{
$text = preg_replace
(
"/(ftp\.|www\.|http:\/\/|https:\/\/|)(.*)(\.)(com|net|co\.uk)/i",
"<a href='http://$2$3$4' target='_blank'>$1$2$3$4</a>",
$text
);
return $text;
}
This code will convert the following "styles" of hyperlinks:
http://www.google.com
www.google.com
google.com
etc., however, the links are forced to HTTP. No matter what you type in, the expression forces HTTP. Is is possible to conditionally include the necessary protocol? For example:
"<a href='[SOME IF-CONDITION GOES HERE TO DECIDE WHAT PROTOCOL TO USE]$2$3$4' target='_blank'>$1$2$3$4</a>",
This condition would be something along the lines of:
if $1 == "http, else if $1 == "https", else if $1 == "ftp",
etc., etc.
Also I realise I'm not accounting for anywhere near enough extensions, this is just test code right now.
Edit: I should note that I'm not looking for "fool proof", unbreakable solutions requiring 200 lines. I don't mind if some obscure domains don't get picked up. I just want the most common domains and URLs to get detected and converted to clickable links.