PHP
  Home arrow PHP arrow Page 3 - 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? 
Google.com  
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 for-loops
    ( Page 3 of 5 )

    We will now move on to the next example of preg_replace_callback(), containing for-loops.

    Suppose you have a list of numbers as follows:


    - 1

    - sum(2, 3)

    - sum(5, 6, 7)

    - sum(11, 20, 37, 40)

    - this is example6


    For those lines containing the keyword sum(), you want to total up only the odd numbers to produce the following results:


    - 1

    - 3

    - 12

    - 48

    - this is example6


    Let’s proceed to solve this using preg_replace_callback():


    <?php

    $str = '- 1

    - sum(2, 3)

    - sum(5, 6, 7)

    - sum(11, 20, 37, 40)

    - this is example6

    ';


    echo preg_replace_callback('/sum((.*?))/', 'process_numbers', $str);


    function process_numbers($matches) {

    $sum = 0;

    foreach(explode(',', $matches[1]) as $n) {

    if ($n%2==1) $sum += $n;

    }

    return $sum;

    }

    ?>


    In the line:


    echo preg_replace_callback('/sum((.*?))/', 'process_numbers', $str);


    we grab all the lines containing the keyword sum().

    Instead of a direct replacement string, PHP makes a call to the callback function process_numbers().

    In the function process_numbers(),


    function process_numbers($matches) {

    $sum = 0;

    foreach(explode(',', $matches[1]) as $n) {

    if ($n%2==1) $sum += $n;

    }

    return $sum;

    }

    ?>

    we use explode() to get hold of each individual number. For each number, we test to see if it’s an odd number. If it is, we add it to the sum. At the end of the loop, we return the sum, which becomes the replacement string for the preg_replace_callback() function.

    The end result is:




    You might think that you can also achieve the same result using a simple for loop with str_replace() function.

    However, imagine the string now becomes a free-form text as shown below:


    $str = '

    - 1 sum(2, 3) sum(5, 6, 7)

    - sum(11, 20, 37, 40) this is a test

    ';


    Without changing any single line, we can use exactly the same code:


    echo preg_replace_callback('/sum((.*?))/', 'process_numbers', $str);


    function process_numbers($matches) {

    $sum = 0;

    foreach(explode(',', $matches[1]) as $n) {

    if ($n%2==1) $sum += $n;

    }

    return $sum;

    }

    ?>


    to produce the following result!


    - 1 3 12

    - 48 this is a test


    This is the beauty of using regular expressions in processing free-form text! And it is the use of the preg_replace_callback() function that allows us to carry out complicated operations that are not possible with the direct preg_replace () function.



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

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - 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





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek