Tuesday, April 26, 2011

Validating the URL

Here I have wrote the recursive PCRE pattern for URL, hope you like it.

Recursive URL pattern features:
-------------------------------------------------------
1. Protocols https|http|ftp|ftps
2. WWW optional or only one.
3. Subdomain (unlimited) (Recursively match the subdomains) & (repeatedly - . at
    same time are not allowed).
4. domain only one (repeatedly - . at same time are not allowed).
5. extention only one mimimum 2, max five (repeatedly . at same time are not allowed).
6. End forward slash (/) is Optional.

<?php

/**
 * is_valid_url ()
 * Validate that given text is valid URL or not.
 *
 * @author   Junaid Atari <mj.atari@gmail.com>
 * @version  1.0
 * @param    string  $str    Text to validate.
 * @return   bool    TRUE on valid | FALSE on invalid.
 */

function is_valid_url ($str)
{
    
//** Return if string not given or empty.
    
if (!is_string ($str)
        || 
trim ($str) == '')
            return 
false;
   
    
//** Recursive url pattern written by Junaid Atari.
    
return preg_match '/^((http|ftp)(s?):\/\/)(www\.)?'.
                        
'([a-z0-9]{1}([\-\.])?)*'.
                        
'([a-z0-9]{1}([\-])?){1}'.
                        
'(\.[a-z]{2,4})\/?$/i'$str ) == 0
        
false
        
true;
}
/*
 +=======================================
 | Example
 +=======================================
*/
$urls = array (
    
'http://www.yahoo.com/',
    
'http://code.google.com',
    
'https://login.live.com/',
    
'http://my.name.is.domain.com.pk/',
    
'https://www.name.is.2k-pcre.co.uk/',
);

foreach (
$urls as $url)
    echo 
$url ." (" . (is_valid_url ($url)
                        ? 
'Valid'
                        
'Not valid') . ")<br />";
/*
 +=======================================
 | Output
 +=======================================
*/

/*
 http://www.yahoo.com/ (Valid)
 http://code.google.com (Valid)
 https://login.live.com/ (Valid)
 http://my.name.is.domain.com.pk/ (Valid)
 https://www.name.is.2k-pcre.co.uk/ (Valid)
*/

0 comments:

Post a Comment