Converts urls in text into clickable JavaScript and PHP custom functions
- 2020-03-30 03:38:16
- OfStack
These days, when writing a small program, you need to use regular expressions to match the URL address in the user's input text, and then replace the URL address with a link that can be clicked. URL address matching, I think this should be everyone in the process of verification often used, here I put together a more complete expression:
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 addresses of HTTP, HTTPS, FTP, FTPS, and IP addresses. Also is the URL address matching algorithm perfect. Using this expression, I wrote two small functions to replace the URL address left by the user with a clickable link. Nothing is too difficult, just use the JavaScript replace() function to replace the URL as link:
The JavaScript version:
/**
* JavaScrit version
* will URL Convert the address to 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:
/**
* PHP version in Silva Code based on the modification
* will URL Convert the address to 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;
}