Skip to content

Instantly share code, notes, and snippets.

@chris-jamieson
Created April 30, 2013 10:52
Show Gist options
  • Save chris-jamieson/5487982 to your computer and use it in GitHub Desktop.
Save chris-jamieson/5487982 to your computer and use it in GitHub Desktop.
Simple PHP snippet to validate a URL using preg_match
<?php
function isValidURL($url){
return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}
// usage
if(!isValidURL($url)){
$message = 'Please enter a valid URL';
echo $message;
}
@hAbd0u
Copy link

hAbd0u commented Mar 6, 2021

By not deeply checking the returned value then you are evaluating 0 and null as the same, from the documentation:

Return Values

preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or false if an error occurred.
Warning

This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment