How can the memory usage be optimized in the preg_replace function to prevent exhausting the memory limit in PHP?

When using the preg_replace function in PHP, it can lead to high memory usage, especially when dealing with large strings or patterns. To optimize memory usage and prevent exhausting the memory limit, you can use the preg_replace_callback function instead. This function allows you to process matches one at a time, reducing the overall memory footprint.

// Example code snippet to optimize memory usage in preg_replace function
$pattern = '/\b(\w+)\b/';
$string = 'Hello world';
$result = preg_replace_callback($pattern, function($matches){
    return strtoupper($matches[0]);
}, $string);

echo $result;