我跑了一些速度测试为chris建议。比起他的代码我:
$str_replace_array = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.');
function tst($pat, $str) {
global $str_replace_array;
$start = microtime(true);
if($pat == '')
str_replace($str_replace_array, '', $str);
else
preg_replace($pat, '', $str);
return microtime(true) - $start;
}
的结果于:
letters
rep 0.00298
norep 0.06953
str_replace 0.00406
numbers
rep 0.02867
norep 0.02612
str_replace 0.01242
mostly_letters
rep 0.00931
norep 0.06649
str_replace 0.00593
mostly_numbers
rep 0.03285
norep 0.02942
str_replace 0.01359
它表明重复正则表达式(与+
增加)时更快更换大块(更少的内存处理?),但没有重复正则表达式稍快,当没有太多需要更换。
此外,str_replace 基本上总是更快(速度的两倍)比正则表达式替换,除非正则表达式匹配整个字符串。
这不符合*完整*正则表达式 – SilentGhost 2010-01-22 15:13:38
找出方法:测试它。试试这三个表达式,并在相当大的一组字符上测试它们:'[^ 0-9。]','[^ 0-9。] +'和'[^ 0-9。] ++'。 – 2010-01-22 15:14:20
@SilentGhost:我没有说它很复杂(当然不是),我说*更复杂*。 – Veger 2010-01-22 15:29:23