These days in writing a small program, you need to use regular expressions to match the user input text URL address, and then replace the URL address can be clicked on the link. URL address Matching, I think this should be done in the validation process is often used, here is the integration of a relatively complete expression of my expressions:
Copy Code code as follows:
var URL =/(https?:\ /\/|ftps?:\ /\/)? ((\d{1,3}\.\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 of the Http,https,ftp,ftps and the IP address. Still be a URL to match the perfect. Using this expression I wrote two small functions to replace the URL of the user's message with clickable links, and nothing too difficult is to use the JavaScript replace () function to implement the replacement URL for link:
JavaScript version:
Copy Code code as follows:
/**
* Javascrit Version
* Convert URL address to full 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:
Copy Code code as follows:
/**
* PHP version modified on the basis of the Silva code
* Convert URL address to full 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 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;
}