Creating a Custom Replacement Function
In some situations you might wish to replace strings based on a somewhat more
complex set of criteria beyond what is provided by PHP??™s default capabilities. For
instance, consider a situation where you want to scan some text for acronyms such as
IRS and insert the complete name directly following the acronym. To do so, you need
to create a custom function and then use the function preg_replace_callback() to
temporarily tie it into the language. Its prototype follows:
mixed preg_replace_callback(mixed pattern, callback callback, mixed str
[, int limit])
The pattern parameter determines what you??™re looking for, while the str parameter
defines the string you??™re searching. The callback parameter defines the name of
the function to be used for the replacement task. The optional parameter limit specifies
how many matches should take place. Failing to set limit or setting it to -1 will
result in the replacement of all occurrences. In the following example, a function
named acronym() is passed into preg_replace_callback() and is used to insert the
long form of various acronyms into the target string:
// This function will add the acronym's long form
// directly after any acronyms found in $matches
function acronym($matches) {
CHAPTER 9 ?– S TRINGS AND REGULAR EXPRESS IONS 247
$acronyms = array(
'WWW' => 'World Wide Web',
'IRS' => 'Internal Revenue Service',
'PDF' => 'Portable Document Format');
if (isset($acronyms[$matches[1]]))
return $matches[1] .
Pages:
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325