Understanding PHP preg_replace_callback and Using Anonymous Functions
This article explains the PHP preg_replace_callback function, its parameters, how to use anonymous functions as callbacks, and demonstrates passing extra arguments via globals or class properties with clear code examples.
The preg_replace_callback function performs a regular‑expression search and replaces matches by invoking a user‑defined callback, allowing dynamic replacement logic.
Signature: preg_replace_callback ( mixed $pattern , callable $callback , mixed $subject [, int $limit = -1 [, int &$count ]] ) : mixed .
Parameters: • pattern : the regex pattern (string or array). • callback : a function that receives the matches array and returns the replacement string. • subject : the string or array to search. • limit : maximum replacements per pattern (default -1 for unlimited). • count : variable that receives the total number of replacements performed.
Anonymous functions are often used as the callback to keep the replacement logic localized and avoid polluting the global namespace.
Example #1 shows a Unix‑style filter that converts the first letter of each paragraph to lowercase using preg_replace_callback with an anonymous function:
<code><?php
/* A Unix‑style filter that lower‑cases the first letter of each paragraph. */
$fp = fopen("php://stdin", "r") or die("can't read stdin");
while (!feof($fp)) {
$line = fgets($fp);
$line = preg_replace_callback(
'|<p>\s*\w|',
function ($matches) {
return strtolower($matches[0]);
},
$line
);
echo $line;
}
fclose($fp);
?></code>When additional data must be accessed inside the callback, two common approaches are demonstrated:
1. Using a global variable:
<code>$param1 = "test";
preg_replace_callback($pregRule, function ($match) {
global $param1;
return $match[1] . $param1 . $match[3];
});</code>2. Using an object‑oriented class property:
<code>class Scrapy {
private $param1 = "test";
public function info() {
preg_replace_callback($pregRule, function ($match) {
return $match[1] . $this->param1 . $match[3];
});
}
}</code>These techniques allow the callback to incorporate external parameters without exposing unnecessary global names.
Conclusion: By leveraging preg_replace_callback with anonymous functions and appropriate parameter‑passing strategies, developers can create flexible, maintainable text‑processing routines in PHP.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.