This question already has an answer here:
- Best way to check if a URL is valid 8 answers
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
}else{
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?
The code below worked for me:
You can also specify RFC compliance and other requirements on the URL using flags. See PHP Validate Filters for more details.
Check if it is a valid url (example.com IS NOT a valid URL)
How to use the function:
Source: http://phpcentral.com/208-url-validation-in-php.html
PHP's
filter_var
function is what you need. Look forFILTER_VALIDATE_URL
. You can also setflags
to fine-tune your implementation.No regex needed....
http://www.php.net/manual/en/function.preg-match.php#93824
but your example URL is over simplified,
(\w+)\.(\w+)
would match it. somebody else mentionedfilter_var
which is simply afilter_var($url, FILTER_VALIDATE_URL)
but it doesn't seem to like non-ascii characters so, beware...Something like might work for you:
OUTPUT:
So basically wherever you notice
false
as return value that is an INVALID URL for you.Regexes are a poor way to validate something as complex as a URL.
PHP's filter_var() function offers a much more robust way to validate URLs. Plus, it's faster, since it's native code.