, OP :
, (, 50 000 ) .
, ( ) , preg_replace_callback, , .
Here is a common function, which in my case with a string of 1.5Mb and ~ 20,000 pairs of replacements was about 10 times faster, although due to the need to split partitions into pieces due to too large “regular expressions” errors could have (in my particular case it was impossible, however).
In my particular case, I was able to optimize this to about a 100-fold increase in performance because my search strings matched a specific pattern. (PHP version 7.1.11 on a 32-bit version of Windows 7).
function str_replace_bulk($search, $replace, $subject, &$count = null) {
$lookup = array_combine($search, $replace);
$result = preg_replace_callback(
'/' .
implode('|', array_map(
function($s) {
return preg_quote($s, '/');
},
$search
)) .
'/',
function($matches) use($lookup) {
return $lookup[$matches[0]];
},
$subject,
-1,
$count
);
if (
$result !== null ||
count($search) < 2
) {
return $result;
}
$split = (int)(count($search) / 2);
error_log("Splitting into 2 parts with ~$split replacements");
$result = str_replace_bulk(
array_slice($search, $split),
array_slice($replace, $split),
str_replace_bulk(
array_slice($search, 0, $split),
array_slice($replace, 0, $split),
$subject,
$count1
),
$count2
);
$count = $count1 + $count2;
return $result;
}
source
share