Check if a string contains nothing but an URL in PHP
50,472
Solution 1
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.
Solution 2
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';
Solution 3
To more securely validate URLs (and those 'non-ascii' ones), you can
-
Check with the filter (be sure to check the manual on which filter suits your situation)
-
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 }
Comments
-
yotka almost 2 years
I am wondering if this is a proper way to check, if a string contains nothing but an URL:
if (stripos($string, 'http') == 0 && !preg_match('/\s/',$string)) { do_something(); }
stripos() checks if the string starts with "http"
preg_match() checks if the string contains spacesIf not so, I assume that the string is nothing but an URL - but is that assumption valid? Are there better ways to achieve this?