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";


Monday, November 14, 2011

Validate the Credit Card Number

/**
 * Check that Credit Card number is valid or not.
 *
 * @author    Junaid Atari <mj.atari@gmail.com>
 * @version   1.1
 * @param     array    $number    Credit Card number
 * @param     string   $cctype    Card Type to check.
 * @return    bool     TRUE on valid | else FALSE
 */

function isCCNumberValid ( $number, $cctype )
{
    if ( !
is_string ( $number)
         || !
trim ( $number ) )
             return 
false;
      
    
$ccs = array (

        /* Patterns written by Junaid Atari */

        // Master Card
        
'master' => '/^(5[1-5]{1})(\d{14})$/',

        
// American Express 
        'amex' => '/^3(4|7)\d{13}$/',
        
        // Discover Card 
        'discover' => '/^6(011|22|4|5)(\d{12}|\d{13}|\d{14})$/', 
        

        // Visa Card 
        'visa' => '/^4(\d{12}|\d{15})$/',

        
// Dinners Club        
        'dinners' => '/^(305|36|38|54|55)(\d{12}|\d{14})$/',

        // Carte Blanche         
        'carte' => '/^(30[0-5]{1})(\d{11})$/', 
        
        // enRoute 
        'enroute' => '/^2(014|149)\d{11}$/', 
        

        // Laser
        'laser' => '/^6(304|706|771|709)(\d{12}|\d{13}|\d{14}'.
                   '|d{\15})$/', 
        
        // Visa Electron 
        'visaelec' => '/^4(17500|917|913|844|508)(\d{10}|\d{12})$/', 
    
);

    if ( !
is_string ( $cctype )
         || !
array_key_exists( strtolower ($cctype) , $ccs ) )
             return 
false;

    return (bool) 
preg_match ( $ccs[$cctype], $number );
} 

Remove Tags from String

/**
 * Remove the tags list from given string.
 *
 * @author     Junaid Atari <mj.atari@gmail.com
>
 * @version    1.1
 * @param      array     $tagsList    Url of page
 * @param      string    $contents    Variable which need to be clean.
 * @return     string    Will direct update the variable in memory.
 */

function removeTags ( array $tagsList, $contents )
{
    foreach ( 
$tagsList as $tag )
    {
        
$tag = trim ( preg_quote ( $tag, '/' ) );
        $contents (string) $contents;
         
        if ( 
$tag != '' )   
            
//** Pattern copyright 2011 Junaid Atari
            
return preg_replace ( '/((<'.$tag.'.*(\/>|>.*<\/'.$tag.
                                  '>)))(\s)?/imsU','', $contents );
        return $contents;
    }
} 

Beautify JSON string

/**
 * pretty_json ()
 * beautify the JSON string
 *
 * Use 'indent' option to select indentation string - by default it's a tab
 *
 * @param    string    $json         Original JSON string
 * @param    array    $options     Encoding options
 * @return    string    Beautified JSON string
 */

function pretty_json ( $json, $options = array() )
{
    
$tokens = preg_split ('|([\{\}\]\[,])|',
              $json, -1, PREG_SPLIT_DELIM_CAPTURE);
    
$result = "";
    
$indent = 0;

    
$ind = "\t";

    if ( isset ( 
$options['indent'] ) )
        $ind = $options['indent'];

    foreach ( 
$tokens as $token )
    {
        if ( 
$token == "" ) continue;

        
$prefix = str_repeat ($ind, $indent); 

        if ( 
$token == "{"
             
|| $token == "[" )
        {
            
$indent++;
            if ( 
$result != ""
                 
&& $result[strlen ($result) - 1] == "\n" )
                    
$result .= $prefix;
              
            
$result .= "$token\n";
        }
        else if ( 
$token == "}"
                  
|| $token == "]" )
        {
            
$indent--;
            
$prefix = str_repeat ( $ind, $indent );
            
$result .= "\n$prefix$token";
        }
        else if (
$token == ",") $result .= "$token\n";
        else 
$result .= $prefix.$token;
    }
  
    return 
$result;
} 

Sunday, July 10, 2011

SQL splitter

Split SQL text into multiple queries and return array.

/**
 * Split the SQL dump code and return the queries array.
 *
 * @version 1.0
 * @access  public
 * @param   string   $sql   SQL code to parse.
 * @return  array    List of queries in array.
 */

function splitSQL ( $query )
{
    
// the regex needs a trailing semicolon
    
$query = trim ( (string) $query ); 

    if ( 
substr ( $query, -1 ) != ";")
        
$query .= ";";

    
// i spent 3 days figuring out this line
    
preg_match_all( "/(?>[^;']|(''|(?>'([^']|\\')*[^\\\]')".
                    "))+;/ixU", $query, $matches, PREG_SET_ORDER ); 

    
$querySplit = "";

    foreach ( 
$matches as $match )
    {
        
// get rid of the trailing semicolon
        
$querySplit[] = substr( $match[0], 0, -1 );
    }

    return 
$querySplit;
} 

Monday, May 23, 2011

Validating the Price

It will check that given text is valid price or not.

Pattern Rules:
1: Supports 0.01 to 
0.99
2: Supports 1.00 to ########.99
3: 0, 0.00, None numeric chars or at least two . (dots) are not allowed.
4: .## (float/precision points) are optional.

/**
 * is_price_valid ()
 * Checkout that given price is valid or not.
 *
 * @author   Junaid Atari <mj.atari@gmail.com>
 * @version  1.0
 * @param    string   $price    String to check.
 * @return   bool     True on valid, False on invalid.
 */ 

function is_price_valid ($price)
{
    if (!
is_string ($price)
        || 
trim ($price) == '')
            return 
false;
  
    
//** Pattern copyright 2011 Junaid Atari
  
    //** Upto 8 chars allowed before . (dot).
    //** Support 2 percisions after . (dot).
    
return preg_match ('/^0\.([0-9][1-9]|[1-9][0-9])'.
                       
'|[1-9][0-9]{0,7}(\.[0-9][0-9])?$/x', $price) == 0
               
? false
               
: true;
}
/*
 +========================================
 | EXAMPLE
 +========================================
*/ 

echo "Is valid price? " . (is_price_valid ('111') ? 'Yes' : 'No');
/* 
 +======================================== 
 | EXAMPLE 
 +======================================== 
*/ 
# Is valid price? Yes

# 1, 0.01, 121.99, 1.00 are valid prices.

Thursday, April 28, 2011

Get Hex colors from string.

It will parse the string and collect all the unique hex colors.

<?php

/**  
 * get_hex_colors ()
 * Collect all unique hex colors from string.
 *
 * @author   Junaid Atari <mj.atari@gmail.com>
 * @version  1.0
 * @param    string   $str    String to check.
 * @return   array    List of unique hex colors
 */

function get_hex_colors ($str)
{
    
//** Pattern copyright 2011 Junaid Atari
    
    //** Hex colors range (A to F , 0 to 9)
    //** Supports 4 chars color code (with hash sign) #000
    //** Supports 7 chars color code (with hash sign) #000000
    //** Case insensitive
    
preg_match_all ("/#[a-f0-9]{6}|#[a-f0-9]{3}/i", $str,
                        
$results, PREG_PATTERN_ORDER);
    
    
//** Remove duplicate hex entries.
    
return array_unique ($results[0]);
}

/*
 +========================================
 | EXAMPLE
 +========================================
*/
$str='
.SearchFormat
{    float:left;
    width:160px; height:17px;
    border:0px;
    border-left:1px dotted #ccc; 
    font-size:12px;
    color:#333;
    margin-top:4px;
    margin-left:30px;
    background-color:#fff;
}

.MainLinks
{    width:890px;
    float:left;
    top:133px;
    left:0px;
    text-align:right;
    color:#CCCCCC;
}
'
;
print_r ( get_hex_colors ($str) );

/*
 +========================================
 | OUTPUT
 +========================================
*/

/*
Array
(
    [0] => #ccc
    [1] => #333
    [2] => #fff
    [3] => #CCCCCC
)
*/