欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php匹配网址的正则 几乎可以匹配任何网址

程序员文章站 2022-04-09 20:55:35
比较简单的 $str = ''; $ismatched = preg_match('/^^((https|http|ftp|rtsp|mms)?:\/\...

比较简单的

$str = '';
$ismatched = preg_match('/^^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+$/', $str, $matches);
var_dump($ismatched, $matches);

几乎可以匹配任何网址:

^((https?|ftp|news):\/\/)?([a-z]([a-z0-9\-]*[\.。])+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-z][a-z0-9_]*)?$ 

实例:

<script type="text/javascript"> 
function isurl(urlstring) 
{ 
regexp = /^((https?|ftp|news):\/\/)?([a-z]([a-z0-9\-]*[\.。])+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-z][a-z0-9_]*)?$/ 
if (urlstring.match(regexp)) 
return "is a url"; 
else 
return "not a url"; 
} 
url = ""; 
alert(isurl(url)); 
</script>