Tuesday, November 22, 2011

Validate the MySQL Timestamp in PHP

/*
 * Validate the MySQL Timestamp
 *
 * @author   Junaid Atari <mj.atari@gmail.com>
 * @version  1.0
 * @param    string  $str   MySQL Timestamp to check
 * @return   bool    TRUE on valid | FALSE
*/
function isValidMySqlTimeStamp ( $str )
{
    
/* PCRE Pattern written by Junaid Atari */
    
if ( !preg_match ( '/^(?<y>19\d\d|20\d\d)\-(?<m>0[1-9]|1[0-2])\-' .
                       
'(?<d>0\d|[1-2]\d|3[0-1]) (?<h>0\d|1\d|2[0-3]' .
                       ')\:
(?<i>[0-5][0-9])\:(?<s>[0-5][0-9])$/',
                       
$str, $date ) )
       return 
false;

    return 
checkdate ( $date['m'], $date['d'], $date['y'] );
}

/*
 +-----------+
 |  Example  |
 +-----------+
*/
var_dump ( isValidMySqlTimeStamp ( '2011-11-26 11:25:26' ) );

/*
 +-----------+
 |  Output  |
 +-----------+
*/
# Output: True 

Validate the MySQL Date in PHP

/*
 * Validate the MySQL Date
 *
 * @author   Junaid Atari <mj.atari@gmail.com>
 * @version  1.0
 * @param    string  $str   MySQL Date to check
 * @return   bool    TRUE on valid | FALSE
*/
function isValidMySqlDate ( $str )
{
    
/* PCRE Pattern written by Junaid Atari */
    
if ( !preg_match ( '/^(?<y>19\d\d|20\d\d)\-(?<m>0[1-9]|1[0-2])'.
                       
'\-(?<d>0\d|[1-2]\d|3[0-1])$/', $str, $date ) )
        return 
false;

    return 
checkdate ( $date['m'], $date['d'], $date['y'] );
}


/*
 +-----------+
 |  Example  |
 +-----------+
*/
var_dump ( isValidMySqlDate ( '2011-11-22' ) );

/*
 +-----------+
 |  Output  |
 +-----------+
*/
# Output: True 

Validate the MySQL Time in PHP

/*
 * Validate the MySQL Time
 *
 * @author   Junaid Atari <mj.atari@gmail.com>
 * @version  1.0
 * @param    string  $str   MySQL Time to check
 * @return   bool    TRUE on valid | FALSE
*/
function isValidMySQLTime ( $str )
{
    
/* PCRE Pattern written by Junaid Atari */
    
return !preg_match ( '/^(?<h>0\d|1\d|2[0-3])\:(?<i>[0-5]\d)\:'.
                         
'(?<s>[0-5]\d)$/', $str )
            ? 
false
            
: true;
}


/*
 +-----------+
 |  Example  |
 +-----------+
*/
var_dump ( isValidMySQLTime ( '11:25:26' ) );

/*
 +-----------+
 |  Output  |
 +-----------+
*/
# Output: True 

Sunday, November 20, 2011

Get the Directories Name by Given Criteria

/*
 * Get the directories name by given criteria.
 *
 * @author    Junaid Atari <mj.atari@gmail.com>
 * @version   1.0
 * @param     string   $dir              Complete path to directory.
 * @param     array    $skipList         Dirs name to be exclude.
 * @param     string   $strictNameRegex  PCRE pattern to filter names
 * @return    array    List of folders name | empty
*/ 
function getDirectryFolders ( 
   
$dir, $skipList = array (), $strictNameRegex = '' )
{
    
$listDir = array ();
    
    if ( !
preg_match ( '@(//|\\\)$@', (string) $dir ) )
        
$dir .= DIRECTORY_SEPARATOR;
    
    
$handler = @opendir ( $dir );
    
    if ( !
$handler )
        return array ();
    
    
$skipList = array_merge ( (array) $skipList, array ( '.', '..' ) );
    
    while ( ( 
$sub = readdir ( $handler ) ) !== false )
    { 
        if ( !
in_array ( $sub, $skipList ) && is_dir ( $dir . $sub ) )
        {
            if ( 
trim ( $strictNameRegex ) )
            {
                if ( (bool) @
preg_match ( $strictNameRegex, $sub ) )
                    
$listDir[ $sub ] = $dir . $sub;
            }
            else
                
$listDir[ $sub ] = $dir . $sub;
        }
    } 
    
    
closedir ( $handler );
    
    return 
$listDir; 
}

/*
+---------+
| Example |
+---------+
*/ 
print_r (
    
getDirectryFolders (
        
'c:\htdocs\web',
        array ( 
'includes' ),
        
'/^[a-z0-9_]+$/i'
    
)
);

/*
+--------+
| Output |
+--------+

Array
(
    [backups] => c:\htdocs\web\backups
    [libraries] => c:\htdocs\web\libraries
    [images] => c:\htdocs\web\images
    [logs] => c:\htdocs\web\logs
    [components] => c:\htdocs\web\components
)

*/ 

Get the Files of Directory by Given Criteria

/*
 * Get the files of directory by given criteria.
 *
 * @author  Junaid Atari <mj.atari@gmail.com>
 * @version 1.0
 * @param   
string  $dir              Path of directory.
 * @param   string  $pattern          Pattern of file name & extesion
 * @param   array   $excludeList      Files list to exclude (name only)
 * @param   string  $strictNameRegex  PCRE pattern to filter files name
 * @return  array   List of folder's files | empty
*/
function getFolderFiles (
   $dir, $pattern = NULL, array $excludeList = array (),
   $strictNameRegex = '' )
{
    
$pattern = !is_string ( $pattern )
                ? 
'*.php'
                
: $pattern;
      
    if ( !
preg_match ( '@(//|\\\)$@', $dir ) )
            
$dir .= DIRECTORY_SEPARATOR;
  
    
$_files = glob ( $dir .DIRECTORY_SEPARATOR . $pattern );
  
    if ( !
count ( $_files ) )
        return array ();
  
    
$filesList = array ();
  
    foreach ( 
$_files as $file )
    {
        
$fName = pathinfo ( $file, PATHINFO_FILENAME );
      
        if ( !
in_array ( $fName, (array) $excludeList ) )
            
$filesList[ $fName ] = $file;
    }
          
    if ( 
trim ( $strictNameRegex ) )
    {
        
$fiList = array ();
      
        
$list = preg_grep (
            $strictNameRegex, array_keys ( $filesList )
        );
      
        if ( !
count ( $list ) )
            return array ();
      
        foreach ( 
$list as $name )
        {
            if ( 
array_key_exists ( $name, $filesList ) )
                
$fiList[ $name ] = $filesList[$name];
        }
      
        
$filesList = $fiList;
    }
  
    return 
$filesList;
}

/*
+---------+
| Example |
+---------+
*/ 

print_r 
(
    
getFolderFiles (
        
'C:/path/to',
        
'CF*.php',
        array ( 
'CTag' ),
        
'/^CF[a-zA-Z0-9_]+$/'
    
)
);

/*
+--------+
| Output |
+--------+

Array
(
    [CF_Comment] => C:/path/to/CF_Comment.php
    [CF_BBTags] => C:/path/to/CF_BBTags.php
    [CF_JavaScript] => C:/path/to/CF_JavaScript.php
)

*/ 

Convert BBTags to HTML Span Tag (Recursive)

/*
 * Convert BBTags to HTML span tag and put their name into CSS class.
 *
 * @author    Junaid Atari <mj.atari@gmail.com>
 * @version   1.0
 * @param     string   $str              String to process.
 * @param     bool     $tagsLowerCase    Convert the names in lowercase.
 * @param     bool     $removeEmptyTags  Remove the empty tags.
 * @return    string   Processed text
*/

function replaceTagsToClasses ( 
   $str, $tagsLowerCase = false, $removeEmptyTags = true )
{
    if ( !
is_string ( $str )
         || !
trim ( $str ) )
             return 
'';
   
    
/* Regex recursive pattern written by Sag-e-Attar Junaid Atari */
    
preg_match_all ( '/\[([a-z]+)\](.*|(?R))\[\/\1\]/imsU',
                     $str, $matches );
   
    if ( !
count ( $matches[1] ) )
        return 
$str;
   
    
$total = count ( $matches[1] );
   
    
$list = array_map (
        
create_function (
            
'$a,$b,$lc,$rmt', 'return $rmt && !trim($b) ? "" :
            "<span class=\"".($lc ? strtolower($a) : $a)."\">".
            trim($b)."</span>";'
        ),
        
$matches[1], $matches[2],
        array_fill ( 0, $total, $tagsLowerCase ),
        
array_fill ( 0, $total, $removeEmptyTags )
    );
   
    return 
replaceTagsToClasses (
        
str_replace ( $matches[0], $list, $str ),
        $tagsLowerCase, $removeEmptyTags
    
);
}

/*
+---------+
| Example |
+---------+
*/

$subs = '[boldA],[/boldA][a][bold][/bold]dsdd[/a][boldA],[/boldA]';
echo 
replaceTagsToClasses ( $subs, true );

/*
+--------+
| Output |
+--------+
<span class="bolda">,</span><span class="a">dsdd</span><span class="bolda">,</span>
*/

Thursday, November 17, 2011

Pakistan's Telephone Numbers Validation

/*
 +===================================================================
 | @title: Pakistan's Telephone numbers Validation
 
| @author: Sag-e-Attar Junaid Atari <mj.atari@gmail.com> 
 | @info: http://en.wikipedia.org/wiki/Telephone_numbers_in_Pakistan
 +===================================================================

 !!! PATTERNS TYPES | SUPPORTED FORMATES !!!

 @ Premium Number
 # Toll Free: 0800 00000 | 0800 000 00 | 080000000
 # Premium Rate: 0900 00000 | 0900 000 00 | 090000000

 @ Mobile Number
 > Mobile code only start with 3
 # Format 1:  (0092)-331-5776662
 # Format 2:  (0092)-331-577 6662
 # Format 2:  (0092) 331 577 6662
 # Format 3:  (+92) 345 5776662
 # Format 4:  (+92)-345-577 6662
 # Format 5:  (+92) 345 577 6662
 # Format 6:  (+92)3455776662
 # Format 7:  +923455776662
 # Format 8:  +92-345-5776662
 # Format 9:  +92 345 577 6662
 # Format 10: 0092-345-577 6662
 # Format 11: 03455776662
 # etc ...

 @ Landline Fixed number
 > Area code cannot start with 3
 # Format 1:  0092 50 000 0000
 # Format 2:  (0092)50 000 0000
 # Format 3:  009250000 0000
 # Format 4:  0092500000000
 # Format 5:  +92 50 000 0000
 # Format 6:  (+92) 50 000 0000
 # Format 7:  +92 50 000 0000
 # Format 8:  +9250 000 0000
 # Format 9:  +9250000 0000
 # Format 10: +9250000 0000
 # Format 11: +9250 0000000
 # Format 12: 0500000000
 # Format 13: 051 0000000
 # Format 14: 061 00000000
 # Format 15: 061 000 000 00
 # Format 16: 0600 000 000
 # Format 17: 0600 000000
 # Format 18: 0600000000
 # Format 19: +92700000000
 # Format 20: 0092600000000
 # Format 21: 0092 600 000 000
 # Format 22: 0092 600000 000
 # Format 23: 0092 600000000
 # etc ...
*/

/*
 * Validate the Pakistan telephone numbers.
 *
 * @author    Junaid Atari <mj.atari@gmail.com>
 * @version   1.0
 * @param     string   $telNumber    Tele number to valid.
 * @return    bool     TRUE on valid | else FALSE
*/

function isPkTelePhoneNumber ( $telNumber )
{
    if ( !
is_string ( $telNumber )
         && !
is_int ( $telNumber ) )
            return 
false;

    
/* All regex patterns written by Sag-e-Attar Junaid Atari */
    
$patterns = array (

        
'premiumNumber'  => '/^0(8|9)00 ?[0-9]{3} ?[0-9]{2}$/', 

        
'mobileNumber'   => '/^((\(((\+|00)92)\)|(\+|00)92)(( |\-)?)' .
                            '(3[0-9]{2})\6|0(3[0-9]{2})( |\-)?)[0-9]' .
                            '{3}( |\-)?[0-9]{4}$/',

        'landlineNumber' => '/^(\((\+|00)92\)( )?|(\+|00)92( )?|0)' .
                            '[1-24-9]([0-9]{1}( )?[0-9]{3}( )?[0-9]' .
                            '{3}( )?[0-9]{1,2}|[0-9]{2}( )?[0-9]{3}' .
                            '( )?[0-9]{3})$/'  
    );

    foreach ( 
$patterns as $pattern )
        
$response[] = preg_match ( $pattern, $telNumber )
                        ? 
true
                        : false;

    return ( 
$response[0] || $response[1] || $response[2] );
}

/*
 +================================
 | Example of usage
 +================================
*/


if ( isPkTelePhoneNumber ( '0092 600 000 000' ) ) 
    echo 'Valid number.' . "\n\n";
else
    echo 
'Invalid Number.' . "\n\n";