Skip to content
PHP Logo

How can one optimize the performance of regular expression replacements in PHP to handle multiple occurrences within a string?

To optimize the performance of regular expression replacements in PHP to handle multiple occurrences within a string, you can use the `preg_replace()` function with the `preg_replace_callback()` function. By using a callback function, you can process each match individually, which can be more efficient than using a simple replacement string. Additionally, you can use the `PREG_SET_ORDER` flag to capture all matches in an array for further processing.

php
$string = "This is a test string with multiple occurrences of 'word'.";
$pattern = "/\b(word)\b/";
$replacement = "replacement";

$result = preg_replace_callback($pattern, function($matches) use ($replacement) {
    return $replacement;
}, $string);

echo $result;