Check if a string contains nothing but an URL in PHP

Use filter_var()

if (filter_var($string, FILTER_VALIDATE_URL)) { 
  // you're good
}

The filters can be even more refined. See the manual for more on this.


In PHP there is a better way to validate the URL http://www.php.net/manual/en/function.filter-var.php

if(filter_var('http://example.com', FILTER_VALIDATE_URL)))
    echo 'this is URL';

To more securely validate URLs (and those 'non-ascii' ones), you can

  1. Check with the filter (be sure to check the manual on which filter suits your situation)

  2. Check to see if there are DNS records

    $string = idn_to_ascii($URL);
    if(filter_var($string, FILTER_VALIDATE_URL) && checkdnsrr($string, "A")){
        // you have a valid URL
    }