What are some best practices for efficiently replacing patterns in a text using PHP functions like str_replace within a loop?

When replacing patterns in a text using PHP functions like str_replace within a loop, it is important to optimize the process for efficiency. One way to do this is by storing the patterns and replacements in arrays outside the loop to avoid unnecessary reinitialization. Additionally, consider using regular expressions with preg_replace for more complex pattern matching.

// Define patterns and replacements outside the loop
$patterns = array('/pattern1/', '/pattern2/', '/pattern3/');
$replacements = array('replacement1', 'replacement2', 'replacement3');

// Text to be processed
$text = "This is a sample text with pattern1, pattern2, and pattern3.";

// Loop through patterns and replacements to replace them in the text
foreach ($patterns as $key => $pattern) {
    $text = preg_replace($pattern, $replacements[$key], $text);
}

echo $text;