In this exercise, we will understand how to validate URLs in PHP with regex. Additionally, you can execute in Laravel or PHP.
It is very difficult to understand the URL is valid or NOT, when user submits the URL.
So in this exercise, I will explain u the efficient and easy way to handle and validate the URL by using Laravel and PHP with Regex.
Below I have explain the different option to validate the URL.
1. Using filter_var() inbuilt function with FILTER_VALIDATE_URL filter.
2. Using preg_match() Regex.
filter_var() with the FILTER_VALIDATE_URL filter
filter_var(variable, filtername, options)
Now let?s see the first way to validate the URL using filter_var() with the FILTER_VALIDATE_URL filter , it is the efficient way to validate the URL.
So I will assign the ?https://www.codesolutionstuff.com? string to $url variable and try to find the the given URL is valid or not by using filter_var() with the FILTER_VALIDATE_URL filter. Please check the following example for more details.
<?php
// Variable to check
$url = "https://www.codesolutionstuff.com";
// Validateurl
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo("Enter URL is a valid URL");
}
else
{
echo("Enter URL is not a valid URL");
}
?>
Filter_var() take three parameters as shown in syntax.
1. Variable
2. Filtername
3. Options
In filter_var() first variable parameter is compulsory and other two parameters are optional.
You can also check the following possible flags while validating URL in PHP
FILTER_FLAG_HOST_REQUIRED ? URL must include hostname (like?https://www.codesolutionstuff.com)
FILTER_FLAG_PATH_REQUIRED ? URL must have a path after the domain name (like?www.codesolutionstuff.com/home
Using preg_match() Regex
Let?s check the other way to validate the URL. Using preg_match() Regex we can find out the given string follows the pattern or not, if the pattern is correct then it will return TRUE otherwise FALSE. Please check the following example for more details.
<?php
$regex = "((https?|ftp)\:\/\/)?";
$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?";
$regex .= "([a-z0-9-.]*)\.([a-z]{2,3})";
$regex .= "(\:[0-9]{2,5})?";
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?";
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?";
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?";
$url = 'https://www.codesolutionstuff.com/';
if (preg_match("/^$regex$/i", $url)) {
echo('Enter URL is a valid URL');
}
?>
I hope you will like the content and it will help you to learn How To Validate URL in PHP with Regex
If you like this content, do share.