How can preg_replace_callback() be used to achieve the desired result in PHP?

When using preg_replace() in PHP, sometimes we need more complex replacements that involve dynamic logic or calculations. In such cases, we can use preg_replace_callback() function, which allows us to define a callback function that will be called for each match found in the input string. The callback function can then return the replacement value based on the match, enabling us to achieve the desired result with more flexibility.

// Example usage of preg_replace_callback() to replace numbers with their square in a string
$input = "Numbers: 1, 2, 3, 4, 5";

$output = preg_replace_callback('/\d+/', function($matches) {
    $number = $matches[0];
    $square = $number * $number;
    return $square;
}, $input);

echo $output; // Output: Numbers: 1, 4, 9, 16, 25