分类分类
更新时间:2026-02-18 18:58:35作者:zhao
最近看到大家都在研究怎么把文中的URL链接转换JAVASCRIPT来编写,我也看了很多,在这里我给大家总结一下,文本中的URL地址转为可点击链接的JavaScript、PHP来自定义函数
很久没有写文章了,这几天在写一个小程序的时候,需要用到正则表达式匹配用户输入文本中的URL地址,然后将URL地址替换成可以点击的链接。URL地址的匹配,我想这应该是大家在做验证处理中常会用到的,这里就把我整合的一个比较完整的表达式给出来:文本中的URL地址转为可点击链接的JavaScript、PHP来自定义函数
这个表达式可以匹配 http,https,ftp,ftps以及IP地址的URL地址。还算是URL地址匹配计较完善的。利用这个表达式我写了两个小函数,将用户留言的URL地址替换成可点击的链接,没有什么太难的,就是利用JavaScript 的 replace() 函数来实现替换 URL 为 link:
JavaScrit 版本
PHP版
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;
}
相关
归墟战纪策略游戏262.92 MBv3.95802026-02-14
下载爆裂老奶策略游戏209.43 MBv1.0.112026-02-14
下载超能下蛋鸭策略游戏395.4 MBv1.2.82026-02-14
下载你好盒子实用工具12.1 MBv2.2.852026-02-14
下载我在峡谷当牛马休闲益智87.95 MBv0.7.12026-02-14
下载抽卡监狱2策略游戏190.75 MBv1.4.92026-02-14
下载Campus社交通讯94.36 MBv1.19.02026-02-14
下载冒险传奇角色扮演141.73 Mv9991.12026-02-14
下载心动次元app社交通讯43.96 Mv1.0.1.32026-02-14
下载致亲爱的我角色扮演1.63Gv1.02026-02-14
下载狼伴侣游戏手机版冒险游戏155.6 Mv1.02026-02-14
下载Loclike社交通讯169.08 Mv2.2.112026-02-14
下载










