Learn PHP Regular Expressions With In An Hours.

1. What are Regular Expressions

The main purpose of regular expressions, also called regex or regexp, is to efficiently search for patterns in a given text. These search patterns are written using a special format which a regular expression parser understands.



Regular expressions are originating from Unix systems, where a program was designed, called grep, to help users work with strings and manipulate text. By following a few basic rules, one can create very complex search patterns.
As an example, let’s say you’re given the task to check wether an e-mail or a telephone number has the correct form. Using a few simple commands these problems can easily be solved thanks to regular expressions. The syntax doesn’t always seems straightforward at first, but once you learn it, you’ll realize that you can do pretty complex searches easily, just by typing in a few characters and you’ll approach problems from a different perspective.

2. Perl Compatible Regular Expressions

PHP has implemented quite a few regex functions which uses different parsing engines. There are two major parser in PHP. One called POSIX and the other PCRE or Perl Compatible Regular Expression.
The PHP function prefix for POSIX is ereg_. Since the release of PHP 5.3 this engine is deprecated, but let’s have a look at the more optimal and faster PCRE engine.
In PHP every PCRE function starts with preg_ such as preg_match or preg_replace. You can read the full function list in PHP’s documentation.

3. Basic Syntax

To use regular expressions first you need to learn the syntax. This syntax consists in a series of letters, numbers, dots, hyphens and special signs, which we can group together using different parentheses.

In PHP every regular expression pattern is defined as a string using the Perl format. In Perl, a regular expression pattern is written between forward slashes, such as /hello/. In PHP this will become a string, ‘/hello/’.

Now, let’s have a look at some operators, the basic building blocks of regular expressions


OperatorDescription
^The circumflex symbol marks the beginning of a pattern, although in some cases it can be omitted
$Same as with the circumflex symbol, the dollar sign marks the end of a search pattern
.The period matches any single character
?It will match the preceding pattern zero or one times
+It will match the preceding pattern one or more times
*It will match the preceding pattern zero or more times
|Boolean OR
-Matches a range of elements
()Groups a different pattern elements together
[]Matches any single character between the square brackets
{min, max}It is used to match exact character counts
\dMatches any single digit
\DMatches any single non digit caharcter
\wMatches any alpha numeric character including underscore (_)
\WMatches any non alpha numeric character excluding the underscore character
\sMatches whitespace character

As an addition in PHP the forward slash character is escaped using the simple slash \. Example: ‘/he\/llo/’

To have a brief understanding how these operators are used, let’s have a look at a few examples:

ExampleDescription
‘/hello/’It will match the word hello
‘/^hello/’It will match hello at the start of a string. Possible matches are hello or helloworld, but not worldhello
‘/hello$/’It will match hello at the end of a string.
‘/he.o/’It will match any character between he and o. Possible matches are helo or heyo, but not hello
‘/he?llo/’It will match either llo or hello
‘/hello+/’It will match hello on or more time. E.g. hello or hellohello
‘/he*llo/’Matches llo, hello or hehello, but not hellooo
‘/hello|world/’It will either match the word hello or world
‘/(A-Z)/’Using it with the hyphen character, this pattern will match every uppercase character from A to Z. E.g. A, B, C…
‘/[abc]/’It will match any single character a, b or c
‘/abc{1}/’Matches precisely one c character after the characters ab. E.g. matches abc, but not abcc
‘/abc{1,}/’Matches one or more c character after the characters ab. E.g. matches abc or abcc
‘/abc{2,4}/’Matches between two and four c character after the characters ab. E.g. matches abcc, abccc or abcccc, but not abc

Besides operators, there are regular expression modifiers, which can globally alter the behavior of search patterns.
The regex modifiers are placed after the pattern, like this ‘/hello/i’ and they consists of single letters such as i which marks a pattern case insensitive or x which ignores white-space characters. For a full list of modifiers please visit PHP’s online documentation.
The real power of regular expressions relies in combining these operators and modifiers, therefore creating rather complex search patterns.

4. Using Regex in PHP


In PHP we have a total of nine PCRE functions which we can use. Here’s the list:
  • preg_filter – performs a regular expression search and replace
  • preg_grep – returns array entries that match a pattern
  • preg_last_error – returns the error code of the last PCRE regex execution
  • preg_match – perform a regular expression match
  • preg_match_all – perform a global regular expression match
  • preg_quote – quote regular expression characters
  • preg_replace – perform a regular expression search and replace
  • preg_replace_callback – perform a regular expression search and replace using a callback
  • preg_split – split string by a regular expression
The two most commonly used functions are preg_match and preg_replace.

Let’s begin by creating a test string on which we will perform our regular expression searches. The classical hello world should do it.
$test_string = 'hello world';
 
If we simply want to search for the word hello or world then the search pattern would look something like this:
preg_match('/hello/', $test_string);
preg_match('/world/', $test_string);
 
If we wish to see if the string begins with the word hello, we would simply put the ^ character in the beginning of the search pattern like this:
preg_match('/^hello/', $test_string);
 
Please note that regular expressions are case sensitive, the above pattern won’t match the word hElLo. If we want our pattern to be case insensitive we should apply the following modifier:
 preg_match('/^hello/i', $test_string);
 
Notice the character i at the end of the pattern after the forward slash.

Now let’s examine a more complex search pattern. What if we want to check that the first five characters in the string are alpha numeric characters.

preg_match('/^[A-Za-z0-9]{5}/', $test_string);
 
Let’s dissect this search pattern. First, by using the caret character (^) we specify that the string must begin with an alpha numeric character. This is specified by [A-Za-z0-9].

A-Z means all the characters from A to Z followed by a-z which is the same except for lowercase character, this is important, because regular expressions are case sensitive. I think you’ll figure out by yourself what 0-9 means.

{5} simply tells the regex parser to count exactly five characters. If we put six instead of five, the parser wouldn’t match anything, because in our test string the word hello is five characters long, followed by a white-space character which in our case doesn’t count.

Also, this regular expression could be optimized to the following form:
preg_match('/^\w{5}/', $test_string);
\w specifies any alpha numeric characters plus the underscore character (_).

6. Useful Regex Functions

Here are a few PHP functions using regular expressions which you could use on a daily basis.

Validate e-mail. This function will validate a given e-mail address string to see if it has the correct form.

function validate_email($email_address)
{
    if( !preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+
                     ([a-zA-Z0-9\._-]+)+$/", $email_address))
    {
        return false;
    } 
    return true;
}
 
Validate a URL

function validate_url($url)
{
    return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?
                      (/.*)?$|i', $url);
}
 
Remove repeated words. I often found repeated words in a text, such as this this. This handy function will remove such duplicate words.

function remove_duplicate_word($text)
{
    return preg_replace("/s(w+s)1/i", "$1", $text);
}
 
Validate alpha numeric, dashes, underscores and spaces

function validate_alpha($text)
{
    return preg_match("/^[A-Za-z0-9_- ]+$/", $text);
}
 
Validate US ZIP codes

function validate_zip($zip_code)
{
    return preg_match("/^([0-9]{5})(-[0-9]{4})?$/i",$zip_code); 
}
 
 

7. Regex Cheat Sheet

Because cheat sheets are cool nowadays, below you can find a PCRE cheat sheet that you can run through quickly anytime you forget something.


Meta Characters

Description
^Marks the start of a string
$Marks the end of a string
.Matches any single character
|Boolean OR
()Group elements
[abc]Item in range (a,b or c)
[^abc]NOT in range (every character except a,b or c)
\sWhite-space character
a?Zero or one b characters. Equals to a{0,1}
a*Zero or more of a
a+One or more of a
a{2}Exactly two of a
a{,5}Up to five of a
a{5,10}Between five to ten of a
\wAny alpha numeric character plus underscore. Equals to [A-Za-z0-9_]
\WAny non alpha numeric characters
\sAny white-space character
\SAny non white-space character
\dAny digits. Equals to [0-9]
\DAny non digits. Equals to [^0-9]

Pattern Modifiers

Description
iIgnore case
mMultiline mode
SExtra analysis of pattern
uPattern is treated as UTF-8



If you like this post please don't forgot to leave comment .

Happy coding Guys :)


Display multilevel subcategory of a category using single table


Today i am going to show all category and its sub-category by using a single table like below example -


My example table like below. In below table all the title which cat_id is '0' that are main category and rest of others are sub category to there parent id.




Now my requirement is to get all category with its subcategory in array .To fulfill this requirement i make a function getCategoryForParentId (parentId=0) like below -

x------------------x----------------x----------------------------------------------------------------------x

function getCategoryForParentId($parent_id = 0) {
$categories = array();
$sql = "SELECT id, cat_id, title FROM category WHERE cat_id='".$parent_id."' ORDER BY title asc";
$result = $this -> result_array($sql);

foreach ($result as $mainCategory) {
$category = array();
$category['id'] = $mainCategory['id'];
$category['name'] = $mainCategory['title'];
$category['parent_id'] = $mainCategory['cat_id'];
$category['sub_categories'] = $this->getCategoryForParentId($category['id']);
$categories[$mainCategory['id']] = $category;
}
return $categories;
}

x--------------------x---------------------------x--------------------------x------------------------------x


Above function return an array with related category and it's subcategory like below example array-


Array
(
    [43] => Array
        (
            [id] => 43
            [name] => ASTM
            [parent_id] => 3
            [sub_categories] => Array
                (
                )

        )

    [44] => Array
        (
            [id] => 44
            [name] => DIN
            [parent_id] => 3
            [sub_categories] => Array
                (
                    [50] => Array
                        (
                            [id] => 50
                            [name] => BS
                            [parent_id] => 44
                            [sub_categories] => Array
                                (
                                    [52] => Array
                                        (
                                            [id] => 52
                                            [name] => UNE
                                            [parent_id] => 50
                                            [sub_categories] => Array
                                                (
                                                )

                                        )

                                )

                        )

                    [49] => Array
                        (
                            [id] => 49
                            [name] => ISO
                            [parent_id] => 44
                            [sub_categories] => Array
                                (
                                    [51] => Array
                                        (
                                            [id] => 51
                                            [name] => GOST
                                            [parent_id] => 49
                                            [sub_categories] => Array
                                                (
                                                )

                                        )

                                )

                        )

                )

        )

)
 
 
Below is my html :

<div class="left_colom">
               <span class="categories_box"> Categories</span>
            <ul class="left_nav">
                <?php
                $categoryAll=$category->getCategory();
                if(!empty($categoryAll)){
                    foreach($categoryAll as $cat){
                        $subcat=$category->getCategoryForParentId($cat['id']);
                        echo "<pre>";
                        print_r($subcat);die;
                                           
                ?>
                <li <?=(!empty($subcat)) ? "id='category'" :""?>><a href="<?=(empty($subcat)) ? $BASE_PATH."product_list.php?catid=".$cat['id'] : "javascript:void()" ?>" title=""><?=$cat['title']?> </a>
                    <?php if(!empty($subcat)){?>
                    <ul style="display:none;" id="subcat">
                    <?php foreach($subcat as $subcatogry){?>
                    <li><a href="#" title=""><?=$subcatogry['name']?></a>
                        <?php if(!empty($subcatogry['sub_categories'])){?>
                        <ul>
                            <?php foreach($subcatogry['sub_categories'] as $subSubcat){?>
                            <li><a href="#" title="ISO"><?=$subSubcat['name']?></a>
                                <?php if(!empty($subSubcat['sub_categories'])){?>
                                <ul>
                                    <?php foreach($subSubcat['sub_categories'] as $subSubSubcat){?>
                                    <li><a href="#" title="GOST"><?=$subSubSubcat['name']?></a></li>
                                    <?php }?>
                                </ul>
                                <?php }?>
                            </li>
                            <?php }?>
                        </ul>
                        <?php }?>
                    </li>
                    <?php }?>
                    </ul>
                </li>
                <?php }} }else{
                    echo '<li><a href="javascript:void();" style="color:red;">Sorry no category found.</a></li>';
                  }
                ?>

            </ul>
</div>


Don't forgot to leave a comment if you like this

Happy coding :)

Call a controller action(function) into another controller action(function) in Yii

Suppose a situation when you need to call a controller action(function) into another controller action (function) in Yii framework .So you just need to follow the below code


For Example : Suppose you have two controller

(1)- UserController
(2)- AdminController

In UserController there are alots of function like Below

(1)- UserController
                 (a)- actionLogin()
                 (b)- actionRegister()
                 (c)- actionCheckLogin()
                 (d)-  ------

(2)- AdminController
                 (a)- actionActivity()
                 (b)- actionUserDetail()
                 (c)-  ------
                 (d)-  ------
 
Now i want to call CheckLogin action into UserDetail action.To fulfill this requirement i just write down below code.

x---------------------x---------------------------x-----------------------x

function actionUserDetail(){

 Yii::import('application.controllers.UserController');  // Here first you have to import that controller

 $check = UserController::CheckLogin ();  // Than call your action

}

x---------------------x---------------------------x-----------------------x

Don't forgot to leave a comment .If you like it .
             
Happy coding guys :)                  

Step by step implementation of PayPal Pay-Flow-Pro Advance


Implementation of paypal pay-flow-pro payment gateway is very easy in php. First of all you will have to be need two thing to implement payflow pro advance -

1-Pay-flow pro advance sdk
2-A testing account on paypal manager (https://manager.paypal.com/)

1- Pay-flow pro advance sdk -  To implement pay-flow-pro .You need two file. PayflowNVPAPI.php and index.php . You just need to create a folder with name "PayFlowTest" and save both of file PayflowNVPAPI.php and index.php togeather into the "PayFlowTest" folder .After that locate your folder in you local host directory or on your server.You can simply test it by entering test credit card number 4111111111111111 and expiry date .Expiry date much be greter than current date.

Note:  After testing successfully don't forgot to change my test account paypal credential with your own.






Now get set and go to implement payflow pro. Just copy the entire below code and  paste in your PayflowNVPAPI.php file.After that you need to create another file index.php


PayflowNVPAPI.php


<?php
//// Helper functions
if (!function_exists('pre')) {
function pre($arr, $heading = NULL) {  
if (!empty($heading)) {    
echo "<p><b>$heading</b></p>";  
}  
echo "<pre><code>\n" . print_r($arr,true) . "\n</pre></code>";
}
}
if (!function_exists('script_url')) {
function script_url() {
 return (@$_SERVER['HTTPS'] ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
}
} 
// Set this to "live" for the live server, "pilot" for the test server, or "sandbox"
// for Payflow accounts created through a Website Payments Pro account on the Sandbox. global $environment;
if (!isset($environment)) $environment = 'pilot';
// parse_payflow_string: Parses a response string from Payflow and returns an
// associative array of response parameters.
function parse_payflow_string($str) {    
$workstr = $str;    
$out = array();         
while(strlen($workstr) > 0) {        
$loc = strpos($workstr, '=');        
if($loc === FALSE) {            
// Truncate the rest of the string, it's not valid            
$workstr = "";            
continue;        
}                 
$substr = substr($workstr, 0, $loc);        
$workstr = substr($workstr, $loc + 1);
// "+1" because we need to get rid of the "="                 
if(preg_match('/^(\w+)\[(\d+)]$/', $substr, $matches)) {            
// This one has a length tag with it.  Read the number of characters            
// specified by $matches[2].            
$count = intval($matches[2]);                         
$out[$matches[1]] = substr($workstr, 0, $count);            
$workstr = substr($workstr, $count + 1);
// "+1" because we need to get rid of the "&"        
} else {            
// Read up to the next "&"            
$count = strpos($workstr, '&');            
if($count === FALSE) {
// No more "&"'s, read up to the end of the string                
$out[$substr] = $workstr;                
$workstr = "";            
} else {
$out[$substr] = substr($workstr, 0, $count);                
$workstr = substr($workstr, $count + 1);
// "+1" because we need to get rid of the "&"            
}        
}    
}         
return $out;
}
// run_payflow_call: Runs a Payflow API call.$params is an associative array of
// Payflow API parameters.  Returns FALSE on failure, or an associative array of response
// parameters on success.
function run_payflow_call($params) {    
global $environment;         
$paramList = array();   
foreach($params as $index => $value) {        
$paramList[] = $index . "[" . strlen($value) . "]=" . $value;    
}        
$apiStr = implode("&", $paramList);         
// Which endpoint will we be using?    
if($environment == "pilot" || $environment == "sandbox")     
$endpoint = "https://pilot-payflowpro.paypal.com/";   
else $endpoint = "https://payflowpro.paypal.com";     
// Initialize our cURL handle.    
$curl = curl_init($endpoint);         
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);         
// If you get connection errors, it may be necessary to uncomment    
// the following two lines:    
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);   
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);         
curl_setopt($curl, CURLOPT_POST, TRUE);    
curl_setopt($curl, CURLOPT_POSTFIELDS, $apiStr);         
$result = curl_exec($curl);    
if($result === FALSE) {      
echo curl_error($curl);      
return FALSE;    
}    
else
return parse_payflow_string($result);
}
?>


Now create an index.php file and just copy the entire below code and paste it into your index.php file .

Note : Dont forget to change you test account credential after successfully testing payflow pro.

Index.php 

<?php
session_start();
include("PayflowNVPAPI.php");
global $environment;
$environment = "sandbox";
//Change it live if you are going for live transaction  require_once('PayflowNVPAPI.php');
//////// //// ////  First, handle any return/responses ////
/*Check if we just returned inside the iframe.  If so, store payflow response and redirect parent window with javascript.Purpose for adding this script is to get responce where ever you want on your php file otherwise paypal return response in iframe*/
if (isset($_POST['RESULT']) || isset($_GET['RESULT']) ) {   $_SESSION['payflowresponse'] = array_merge($_GET, $_POST);   echo '<script type="text/javascript">window.top.location.href = "' . script_url() .  '";</script>';   exit(0); }  echo "<span style='font-family:sans-serif;font-size:160%;font-weight:bold;'>PayPal Payments Advanced - Demo On phpsollutions.blogspot.com</span> <p style='margin-left:1em;font-family:monospace;'>
Hosted checkout page (Layout C) embedded in your site as an iframe</p>
<hr/>";
//Check whether we stored a server response.If so, print it out.
if(!empty($_SESSION['payflowresponse'])) {
$response= $_SESSION['payflowresponse'];
unset($_SESSION['payflowresponse']);
$success = ($response['RESULT'] == 0);
/*Now Here you can print all responce returning from paypal sucess or error   respectivelly */ 
if($success) echo "<span style='font-family:sans-serif;font-weight:bold;'>Transaction approved! Thank you for your order.</span>";
else echo "<span style='font-family:sans-serif;'>Transaction failed! Please try again with another payment method.</span>";
echo "<pre>(server response follows)\n";
print_r($response);
echo "</pre>
";
exit(0);
}
// Otherwise, begin hosted checkout pages flow 
//Build the Secure Token request
$request = array("PARTNER" => "PayPal", //change it paypal manager account setting 
"VENDOR" => "nitinpayflowtest", //change it paypal manager account setting 
"USER" => "nitinpayflowtest", //change it paypal manager account setting 
"PWD" => "nitin123!",  //change it paypal manager account setting 
"TRXTYPE" => "S", //'S'=>Sale,'A'=>Authorize,'D'=>Delay Captured, 
"AMT" => "149",   "CURRENCY" => "USD",   "CREATESECURETOKEN" => "Y", //Set Y=>'Yes' to create secure token 
"SECURETOKENID" => uniqid('MySecTokenID-'), //Should be unique, never used before 
"RETURNURL" => script_url(), 
"CANCELURL" => script_url(), 
"ERRORURL" => script_url(),  // In practice you'd collect billing and shipping information with your own form, // then request a secure token and display the payment iframe. // --> See page 7 of https://cms.paypal.com/cms_content/US/en_US/files/developer/Embedded_Checkout_Design_Guide.pdf // This example uses hardcoded values for simplicity.  
"BILLTOFIRSTNAME" => "salman", 
"BILLTOLASTNAME" => "ahmad", 
"BILLTOSTREET" => "123 Main St.", 
"BILLTOCITY" => "San Jose", 
"BILLTOSTATE" => "CA", 
"BILLTOZIP" => "95101", 
"BILLTOCOUNTRY" => "US",  
"SHIPTOFIRSTNAME" => "Jane", 
"SHIPTOLASTNAME" => "Smith", 
"SHIPTOSTREET" => "1234 Park Ave", 
"SHIPTOCITY" => "San Jose", 
"SHIPTOSTATE" => "CA", 
"SHIPTOZIP" => "95101", 
"SHIPTOCOUNTRY" => "US", );
//Run request and get the secure token response
$response = run_payflow_call($request);
if ($response['RESULT'] != 0) {
pre($response, "Payflow call failed");
exit(0);
}else {
$securetoken = $response['SECURETOKEN'];
$securetokenid = $response['SECURETOKENID'];
}
if($environment == "sandbox" || $environment == "pilot")
$mode='TEST';
else
$mode='LIVE';
echo '<div style="border: 1px dashed; margin-left:40px; width:492px; height:567px;">
';
// wrap iframe in a dashed wireframe for demo purposes
echo "<iframe src='https://payflowlink.paypal.com?SECURETOKEN=$securetoken&SECURETOKENID=$securetokenid&MODE=$mode' width='490' height='565' border='0' frameborder='0' scrolling='no' allowtransparency='true'>\n</iframe>";
echo "</div><p style='margin-left:40px;font-family:monospace;'>(end of hosted iframe, marked with dashed line)</p>
";
?>


2-Testing account on paypal manager (https://manager.paypal.com/):

To create a testing account please click on this link create test account .







If you having problem during implementation of paypal payflow-pro advance then you can directly contact me threw comments .


Please don't leave with out posting comment 

Chears:)

Happy coding Guys