如果您正在寻找最有效的方法,以下代码的结果是:
预置:1.03257489204
array_intersect:2.62625193596
strpos:0.814728021622
看起来循环数组并使用 strpos 进行匹配是最有效的方法。
$arr=array("*" , "$" , "#" , "!");
$string="this * is very beautiful but $ is more important in life.";
$time = microtime(true);
for ($i=0; $i<100000; $i++){
$r = '~[' . preg_quote(implode('', $arr)) . ']~';
$str = "this * is very beautiful but $ is more important in life.";
preg_match_all($r, $str, $matches);
}
echo "preg:". (microtime(true)-$time)."\n";
$time = microtime(true);
for ($i=0; $i<100000; $i++){
$str = str_split($string);
$out = array_intersect($arr, $str);
}
echo "array_intersect:". (microtime(true)-$time)."\n";
$time = microtime(true);
for ($i=0; $i<100000; $i++){
$res = array();
foreach($arr as $a){
if(strpos($string, $a) !== false){
$res[] = $a;
}
}
}
echo "strpos:". (microtime(true)-$time)."\n";