REGEX – Regular expression to match a URL

This one compares the URL where it will first look for http://, https:// or check for it presence at all.

Next it looks up the domain name which consists of one or more numbers, letters, dots, or hyphens followed by another dot then two to six letters or dots. The later section “?([\da-z\.-]+)\” is optional files and directories.

Then the inside part “.([a-z\.]{2,6})([\/\w \.-]*)” matches any number of forward slashes, letters, numbers, underscores, spaces, dots, or hyphens. Then we say that this group can be matched as many times as we want. Pretty much this allows multiple directories to be matched along with a file at the end. I have used the star instead of the question mark because the star says zero or more, not zero or one.

If a question mark was to be used there, we could match only one file/directory. Then a trailing slash is matched, but it can be optional. Finally we end with the end of the line.

$valid_url = "/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/";

$url= $_POST['url'];
if(preg_match($valid_url, $url)){
$message = "Valid URL. You may proceed.";
$message = "Please enter a Valid URL.";

One Reply to “REGEX – Regular expression to match a URL”

Leave a Reply

Your email address will not be published. Required fields are marked *