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.
blog comments powered by Disqus |
|
|
|
|
|
|
|