URL正则表达式匹配方案
近期开发小程序时,需求涉及利用正则表达式识别用户输入文本中的URL,并将其转化为可点击的超链接。URL匹配是验证处理中的常见场景,此处分享一个经过整合且较为完善的正则表达式方案。
复制代码 代码如下: 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;
该表达式能够覆盖http、https、ftp、ftps协议以及IP地址形式的URL,匹配度较高。基于此表达式,编写了两个小函数,用于将留言中的URL替换为可点击链接,核心逻辑是利用JavaScript的replace()函数进行替换操作。
JavaScript版:
复制代码 代码如下: /** * JavaScrit 版本 * 将URL地址转化为完整的A标签链接代码 */ 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版:
复制代码 代码如下: /** * PHP 版本 在 Silva 代码的基础上修改的 * 将URL地址转化为完整的A标签链接代码 */ /** ============================================= 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; }