我只见过开发人员在使用 strpos
检查子字符串是否存在时使用严格比较:
if (strpos($haystack,$needle) !== false) {
}
今天我想到一个可以使用is_numeric
ins
if (is_numeric(strpos($haystack,$needle))) {
}
是否有理由使用一个而不是另一个(特别是在这个用例中)?
如果您仔细想想,strpos
的目的是返回子字符串的位置。只有不存在,才会返回false。位置是一个数字。因此,is_numeric
完全可以从语义上考虑。
最佳答案
我已经创建了一个基准。 Case 通过与假值比较来检查
总是比通过 is_numeric 检查
更快。
// Init a big string array
for($i = 0; $i < 10000; $i++){
$str[] = 'a'.rand().'b'.rand();
}
// Case comparing with false value
$time1 = microtime(true);
foreach($str as $st){
$res[] = strpos($st,rand(0, count(array('b', 'c')) - 1 )) !== false;
}
$time2 = microtime(true);
echo $time2-$time1.'<br/>';
// Case 'is_numeric'
$time3 = microtime(true);
foreach($str as $st){
$res[] = is_numeric(strpos($st,rand(0, count(array('b', 'c')) - 1 )));
}
$time4 = microtime(true);
echo $time4-$time3;
//Time 1:
//0.018877029418945
//0.020556926727295
//Time 2:
//0.016352891921997
//0.016934871673584
//Time 3:
//0.0121009349823
//0.01330304145813
//Time 4:
//0.017507076263428
//0.01904296875
关于php - 使用 strpos 检查字符串中是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34802829/