How can the use of regular expressions in PHP functions like preg_replace be optimized for better performance when working with arrays of strings?

When working with arrays of strings in PHP functions like preg_replace, it is important to optimize the regular expressions used for better performance. One way to do this is by pre-compiling the regular expressions outside of the loop that iterates over the array. This way, the regular expression is only compiled once and can be reused for each string in the array, improving efficiency.

$patterns = array('/pattern1/', '/pattern2/', '/pattern3/');
$replacements = array('replacement1', 'replacement2', 'replacement3');

$compiled_patterns = array();
foreach($patterns as $pattern){
    $compiled_patterns[] = preg_replace($pattern, '', '');
}

foreach($strings_array as $string){
    echo preg_replace($compiled_patterns, $replacements, $string);
}