When writing a mini program these days, you need to use regular expressions to match the URL address in the text entered by the user, and then replace the URL address with a link that you can click on. I think this is what you often use in verification processing. Here I will give a relatively complete expression I integrated:
The code copy is as follows:
var URL = /(https?:////|ftps?://///)?((/d{1,3}/./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 addresses of http, https, ftp, ftps and IP addresses. It is still quite perfect for URL address matching. Using this expression, I wrote two small functions to replace the URL address of the user's message with a clickable link. There is nothing too difficult. It is to use the JavaScript replace() function to implement the replacement URL to link:
JavaScript version:
The code copy is as follows:
/**
* JavaScript version
* Convert URL address into complete A-tagged 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 copy is as follows:
/**
* The PHP version is modified based on Silva code
* Convert URL address into complete A-tagged 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;
}