Backend Development 4 min read

Understanding PHP's preg_replace_callback Function and How to Use Callbacks

This article explains PHP's preg_replace_callback function, details its parameters, demonstrates using anonymous functions for callbacks, and shows how to pass additional arguments via globals or class properties with clear code examples.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP's preg_replace_callback Function and How to Use Callbacks

The preg_replace_callback function performs a regular‑expression search and replaces matches using a user‑defined callback, allowing dynamic replacement logic in PHP.

Its signature is preg_replace_callback ( mixed $pattern , callable $callback , mixed $subject [, int $limit = -1 [, int &$count ]] ) : mixed , where $pattern is the regex pattern, $callback receives the matches array, $subject is the target string, $limit limits replacements, and $count (if provided) receives the number of replacements performed.

The callback must accept an array of matches and return the replacement string; using an anonymous function keeps the callback definition close to its usage and avoids polluting the global namespace.

Example #1 demonstrates reading from STDIN and converting the first character of each paragraph to lowercase using an anonymous function:

<?php
/* A Unix‑style filter that converts the first uppercase letter of a paragraph to lowercase. */
$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);
?>

When additional data needs to be accessed inside the callback, two common approaches are:

Using a global variable:

$param1 = "test";
preg_replace_callback($pregRule, function ($match) {
    global $param1;
    return $match[1] . $param1 . $match[3];
});

or

Encapsulating the data in a class and accessing it via $this :

class Scrapy {
    private $param1 = "test";
    public function info() {
        preg_replace_callback($pregRule, function ($match) {
            return $match[1] . $this->param1 . $match[3];
        });
    }
}

Both methods allow the callback to utilize external parameters without exposing unnecessary global names.

Summary : By leveraging preg_replace_callback with anonymous functions and appropriate parameter‑passing techniques, developers can create flexible, maintainable text‑processing routines in PHP.

BackendPHPregexcallbackAnonymous Functionpreg_replace_callback
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.