0

I have a string which may be an URL. I want to determine if its a Http/FTP URL by a regex. If the string is valid URL then I will make it hyperlink and a blue color etc, if its not an URL based on ture or false of regex exp i want to decide further..

Whats is best Regex for it ?

3
  • possible duplicate of PHP validation/regex for URL Commented Jan 30, 2011 at 4:57
  • 2
    Have you Googled "URL regular expression"? And what flavor regexp / for which language? Commented Jan 30, 2011 at 4:57
  • possible duplicate of Regex to match URL Commented Jan 30, 2011 at 5:15

3 Answers 3

1
 isUrlValid(str)
{
   var pattern = new RegExp('^(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*(\\?[;&a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?$', 'g'); 
   return pattern.test(str);
}

It passes all this test cases:

Sign up to request clarification or add additional context in comments.

Comments

0

This perl code is pretty accurate, probably not perfect. Group 1 contains either http or ftp

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

Comments

0

Just in case you want to know if the url really exists:

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);
}

1 Comment

How long does that function take?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.