PHP
  Home arrow PHP arrow Page 2 - The preg_replace_callback() function in PHP
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

The preg_replace_callback() function in PHP
By: K.K.Sou
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 2
    2008-09-09


    Table of Contents:
  • The preg_replace_callback() function in PHP
  • preg_replace_callback() with conditional statements
  • preg_replace_callback() with for-loops
  • Using preg_replace_callback() to produce a running sequence
  • Using preg_replace_callback() in classes

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    The preg_replace_callback() function in PHP - preg_replace_callback() with conditional statements
    ( Page 2 of 5 )

    I am sure the first example did not impress you at all, since you can achieve the same objective using preg_replace(). So let’s now extend the script so that you can start to appreciate the beauty of the preg_replace_callback() function.

    Suppose now instead of returning the date in YYMMDD format, you need to return the date in YYYYMMDD format. In this example, instead of returning the date as "081225," we want to return "20081225."

    We also add one assumption here: for YY>=’70’, it refers to years between 1970 and 1999. For YY<’70’, it refers to years between 2000 and 2069.

    So "701225" will become "19701225," and "691225" will become "20691225."

    You will most probably find this an easy task to do with a combination of preg_match() and preg_replace().

    However, suppose now I tell you that we would like to achieve the above in just one line? Do you think it’s possible?

    Before I show you the one-liner version, let me show you the “expanded” version first:

    <?php

    $pattern = '|(d{2})/(d{2})/(d{2})|';

    echo preg_replace_callback($pattern, 'process', '12/25/08')."n";

    echo preg_replace_callback($pattern, 'process', '12/25/70')."n";

    echo preg_replace_callback($pattern, 'process', '12/25/69')."n";

    echo preg_replace_callback($pattern, 'process', '12/25/98')."n";


    function process($matches) {

    if ($matches[3]>=70)

    $prefix = '19';

    else

    $prefix = '20';

    return $prefix.$matches[3].$matches[1].$matches[2];

    }

    ?>


    And here’s the output:




    As you can see, you can do any kind of processing you like to generate the replacement string. In this example, we simply test if the year, which is in the array element $matches[3], is greater or less than 70. The prefix is generated accordingly and prepended to the start of the original replacement string.

    Notice that the callback function uses a simple if…then…else statement. We can condense the callback function into just one line:


    <?php

    $pattern = '|(d{2})/(d{2})/(d{2})|';

    echo preg_replace_callback($pattern, 'process', '12/25/08')."n";

    echo preg_replace_callback($pattern, 'process', '12/25/70')."n";

    echo preg_replace_callback($pattern, 'process', '12/25/69')."n";

    echo preg_replace_callback($pattern, 'process', '12/25/98')."n";


    function process($matches) {

    return ($matches[3]>=70?'19':'20').$matches[3].$matches[1].$matches[2];

    }

    ?>


    And since the callback function is a simple one, preg_replace_callback() allows us to use an anonymous function as the callback function, using create_function().


    <?php

    echo preg_replace_callback('|(d{2})/(d{2})/(d{2})|',

    create_function('$matches',

    'return ($matches[3]>=70?"19":"20").$matches[3].$matches[1].$matches[2];'),

    '12/25/08');

    ?>


    Note the use of single quotes so that the ‘$’ sign preceding each variable remains. If you want to use double quote, you need to escape the ‘$’ sign as follows.


    <?php

    echo preg_replace_callback('|(d{2})/(d{2})/(d{2})|',

    create_function('$matches',

    "return ($matches[3]>=70?'19':'20').$matches[3].$matches[1].$matches[2];"),

    '12/25/08');

    ?>


    A word of caution here. Each call to create_function() will consume some memory. So if your application makes too many calls to a callback function that uses an anonymous function, you might run out of memory!




     
     
    >>> More PHP Articles          >>> More By K.K.Sou
     

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    Stay green...Green IT