用于URL验证的正则表达式

时间:2011-01-30 04:53:27

标签: regex

我有一个字符串,可能是一个URL。我想通过正则表达式来确定它是否是一个Http / FTP URL。如果字符串是有效的URL,那么我将使它成为超链接和蓝色等,如果它不是基于正则表达式的真实或错误的URL我想进一步决定..

什么是最好的正则表达式呢?

2 个答案:

答案 0 :(得分:0)

这个perl代码非常准确,可能并不完美。第1组包含httpftp

if ($str =~ /^(http|ftp):\/\/[\w.%@]+(:?[?].*)?/) {
    print "matches $1\n";
} else {
    print "no match\n";
}

答案 1 :(得分:0)

万一你想知道网址是否真的存在:

function url_exist($url){//se passar a URL existe
    $c=curl_init();
    curl_setopt($c,CURLOPT_URL,$url);
    curl_setopt($c,CURLOPT_HEADER,1);//get the header
    curl_setopt($c,CURLOPT_NOBODY,1);//and *only* get the header
    curl_setopt($c,CURLOPT_RETURNTRANSFER,1);//get the response as a string from curl_exec(), rather than echoing it
    curl_setopt($c,CURLOPT_FRESH_CONNECT,1);//don't use a cached version of the url
    if(!curl_exec($c)){
        //echo $url.' inexists';
        return false;
    }else{
        //echo $url.' exists';
        return true;
    }
    //$httpcode=curl_getinfo($c,CURLINFO_HTTP_CODE);
    //return ($httpcode<400);
}
相关问题