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_existsstrtolower ($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, -1PREG_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, -) != ";")
        
$query .= ";";

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

    
$querySplit "";

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

    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,
                        
$resultsPREG_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
)
*/ 

Remove inline CSS from HTML

Here, Please checkout the code:

<?php
/** 
 * remove_inline_css ()
 * Remove the inline CSS styles for HTML tags.
 *
 * @author   Junaid Atari <mj.atari@gmail.com>
 * @version  1.0
 * @param    string   $subject    String to remove styles.
 * @return   string   Filtered HTML string.
 */

function remove_inline_css ($subject)
{
    
//** Return if invalid type given.
    
if (!is_string ($subject)

        || trim ($subject) == '')
            return 
'No text given.';
    
    
//** Create the anonymous function on Runtime.
    
$cr create_function ('$matches',

              'return str_replace ($matches[2], "", $matches[0]);');
    
    
//** Pattern copyright 2011 Junaid Atari
    //** Return with Regex, only find the style=".*" attribute

         of any tag
    //** and replace using callback.
    
return preg_replace_callback ('/(<[^>]+( style=".*").*>)/iU',
            
$cr,
            
$subject);
}

/*
 +========================================
 | EXAMPLE
 +========================================
*/

$subject '<a target="_blank" style="color:red;">This is my test</a>';
echo remove_inline_css ($subject); 


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

//<a target="_blank">This is my test</a>