Home >Web Front-end >JS Tutorial >JavaScript and PHP custom functions that convert URL addresses in text into clickable links_javascript skills
When writing a small program these days, I need to use regular expressions to match the URL address in the text input by the user, and then replace the URL address with a clickable link. URL address matching, I think this should be something that everyone often uses in verification processing. Here is a relatively complete expression that I integrated:
This expression can match URL addresses of http, https, ftp, ftps and IP addresses. It is still a relatively complete URL address matching calculation. 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. Just use JavaScript's replace() function to replace the URL with link:
JavaScript version:
return text;
};
PHP version:
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;
}