Jack Ben Jack Ben - 4 years ago 144
PHP Question

check if a string is a URL

I've seen many questions but wasn't able to understand how it works
as I want a more simple case.

If we have text, whatever it is, I'd like to check if it is a URL or not.

$text = "something.com"; //this is a url

if (!IsUrl($text)){
echo "No it is not url";
exit; // die well
echo "Yes it is url";
// my else codes goes

function IsUrl($url){
// ???

Is there any other way rather than checking with JavaScript in the case JS is blocked?

Answer Source


    $regex = "((https?|ftp)\:\/\/)?"; // SCHEME 
    $regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass 
    $regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP 
    $regex .= "(\:[0-9]{2,5})?"; // Port 
    $regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path 
    $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query 
    $regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor 

       if(preg_match("/^$regex$/", $url)) 
               return true; 

but your example URL is over simplified, (\w+)\.(\w+) would match it. somebody else mentioned filter_var which is simply a filter_var($url, FILTER_VALIDATE_URL) but it doesn't seem to like non-ascii characters so, beware...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download