How to check the validation of URL www and href in PHP

When a URL is submitted from an input by the user, it is the to check this URL is valid or not before taking any action on it.

Here we’ll provide the simple PHP code to validate a URL in PHP. Using user define a function with Filter, we can easily validate a URL in PHP.

Example

<?php
$website = '';
$data = 'http://google.com'; // change website url like $data = 'www.google.com';
function get_string_between_data($string, $start, $end){
	$string = ' ' . $string;
	$ini = strpos($string, $start);
	if ($ini == 0) return '';
	$ini += strlen($start);
	$len = strpos($string, $end, $ini) - $ini;
	$string_find  = substr($string, $ini, $len);
	$finalstring = str_replace(" ", "", $string_find);
	return $finalstring = str_replace($string_find, $finalstring, $string);
}

$websitedata = get_string_between_data($data, 'www.', '.');

if(empty($website) && !empty($websitedata))
{
	$website_re = '/(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/';
	preg_match_all($website_re, $websitedata, $websitematches);
	$website = $websitematches[0][0];

	if(empty($website) && !empty($websitedata))
	{
		$website_re = '/(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|WWW\.[^\s]+\.[^\s]{2,})/';
		preg_match_all($website_re, $websitedata, $websitematches);
		$website = $websitematches[0][0];
	}
}
else
{
	$website_re = '/(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/';
	preg_match_all($website_re, $data, $websitematches);
	$website = @$websitematches[0][0];

	if(empty($website))
	{
		$website_re = '/(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|WWW\.[^\s]+\.[^\s]{2,})/';
		preg_match_all($website_re, $data, $websitematches);
		$website = @$websitematches[0][0];
	}
}

if(!empty($website))
{
	echo "Correct URL";
}
else
{
	echo "Incorrect URL";
}

?>

Leave a Reply

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