This article mainly describes how to convert the URL address in the text into JavaScript and PHP udfs with clicklinks. If you need a small program, refer to the following days, you need to use a regular expression to match the URL address in the user input text, and then replace the URL address with a clickable link. URL address matching. I think this is often used in verification. Here we will give a complete expression that I have integrated:
The Code is as follows:
Var URL =/(https? : \/| Ftps? :\/\/)? (\ D {1, 3} \. \ d {1, 3} \. \ d {1, 3}) (: [0-9] + )? | (Localhost) (: [0-9] + )? | ([\ W] + \.) (\ S +) (\ w {2, 4}) (: [0-9] + )?) (\/? ([\ W #! :.? + = & % @! \-\/] + ))? /Ig;
This expression can match the URL addresses of http, https, ftp, ftps, and IP addresses. It is still well-regarded for URL address matching. Using this expression, I wrote two small functions to replace the URL address of the user's message with the clickable link. Nothing is too difficult, that is, using the replace () of JavaScript () function to replace the URL with link:
JavaScript version:
The Code is as follows:
/**
* JavaScrit version
* Convert the URL address to the complete A tag link code
*/
Var replaceURLToLink = function (text ){
Text = text. replace (URL, function (url ){
Var urlText = url;
If (! Url. match ('^ https? :\/\/')){
Url = 'HTTP: // '+ url;
}
Return ''+ urlText + '';
});
Return text;
};
PHP version:
The Code is as follows:
/**
* The PHP version is modified based on the Silva code
* Convert the URL address to the complete A tag link code
*/
/** =================================================== ==========
NAME: replace_URLtolink ()
VERSION: 1.0
AUTHOR: J de Silva
DESCRIPTION: returns VOID; handles converting
URLs into clickable links off a string.
TYPE: functions
========================================================== ===== */
Function replace_URLtolink ($ text ){
// Grab anything that looks like a URL...
$ Urls = array ();
// Build the patterns
$ Scheme = '(https? \: \/| Ftps? \:\/\/)? ';
$ Www = '([\ w] + \.)';
$ Local = 'localhost ';
$ Ip = '(\ d {1, 3} \. \ d {1, 3} \. \ d {1, 3} \. \ d {1, 3 })';
$ Name = '([\ w0-9] + )';
$ Tld = '(\ w {2, 4 })';
$ Port = '(: [0-9] + )? ';
$ The_rest = '(\/? ([\ W #! :.? + = & % @! \-\/] + ))? ';
$ Pattern = $ scheme. '('. $ ip. $ port. '| '. $ www. $ name. $ tld. $ port. '| '. $ local. $ port. ')'. $ the_rest;
$ Pattern = '/'. $ pattern. '/is ';
// Get the URLs
$ C = preg_match_all ($ pattern, $ text, $ m );
If ($ c ){
$ Urls = $ m [0];
}
// Replace all the URLs
If (! Empty ($ urls )){
Foreach ($ urls as $ url ){
$ Pos = strpos ('HTTP \: \/', $ url );
If ($ pos & $ pos! = 0) |! $ Pos ){
$ Fullurl = 'HTTP: // '. $ url;
} Else {
$ Fullurl = $ url;
}
$ Link = ''. $ url .'';
$ Text = str_replace ($ url, $ link, $ text );
}
}
Return $ text;
}