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

preg_replace_callback() with conditional statements - 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

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
 

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: