Running tests, I found this:
while (strpos($str, '__') !== false) { $str = str_replace('__', '_', $str); }
will be consistently faster than this:
$str = preg_replace('/[_]+/', '_', $str);
I generated test strings of various lengths as follows:
$chars = array_merge(array_fill(0, 50, '_'), range('a', 'z')); $str = ''; for ($i = 0; $i < $len; $i++) { // $len varied from 10 to 1000000 $str .= $chars[array_rand($chars)]; } file_put_contents('test_str.txt', $str);
and tested with these scripts (runs separately, but in the same lines for each value of $ len):
$str = file_get_contents('test_str.txt'); $start = microtime(true); $str = preg_replace('/[_]+/', '_', $str); echo microtime(true) - $start;
and
$str = file_get_contents('test_str.txt'); $start = microtime(true); while (strpos($str, '__') !== false) { $str = str_replace('__', '_', $str); } echo microtime(true) - $start;
For shorter lines, the str_replace () method was 25% faster than the preg_replace () method. The longer the string, the smaller the difference, and str_replace () is always faster.
I know that some would prefer one method over another for reasons other than speed, and I would be happy to read comments regarding the results, test method, etc.