Validate URL Use Regular Expression (Regex) In PHP
Posted by in PHP January 31, 2012 Leave a comment

This is just a simple PHP function that verify a input string to see if it’s a valid URL with right format or not. It uses regex expression to match.

This function works for almost cases (website url) but it’s not exhaustive, I’m sure :)

PHP Validate URL function

<?php
	function validate_url($url)
	{
		if (!preg_match("#^http(s)?://[a-z0-9-_.]+\.[a-z]{2,4}#i",$url))
			return "0";
		return "1";
	}
?>

Usage

<?php
	$url = "http://4rapiddev.com";
 
	if(validate_url($url) == "1")
		echo "It's a valid URL";
	else
		echo "It is NOT a valid URL";
?>

Output

It's a valid URL

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com