Home arrow PHP arrow Page 3 - The preg_replace_callback() function in PHP

preg_replace_callback() with for-loops - PHP

The preg_replace_callback() function is an under-utilized and little documented PHP function that you will find useful and powerful in many situations, especially if you have been actively using preg_match() and preg_replace(). In this article, you will find a clear explanation of what this function does, together with carefully crafted examples that illustrate some of its uses.

TABLE OF CONTENTS:
  1. The preg_replace_callback() function in PHP
  2. preg_replace_callback() with conditional statements
  3. preg_replace_callback() with for-loops
  4. Using preg_replace_callback() to produce a running sequence
  5. Using preg_replace_callback() in classes
By: K.K.Sou
Rating: starstarstarstarstar / 3
September 09, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: