php - 使用 strpos 检查字符串中是否存在

标签 php strpos

我只见过开发人员在使用 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/

相关文章:

php - 多维数组 json_decode (第一级)

php - : insert multiple rows via a php array into mysql 的代码重写

javascript - 当我们点击它时如何聚焦 Accordion 顶部标题

php - ZF2 : How to make Zend\Validator\Hostname accept url strings with and without http://or https://

php - 如何使 strpos 不区分大小写

php - 如何使用 strpos 将数据库中的常见垃圾邮件字段与表单提交进行匹配?

php - 使用 strpos() 查找整个单词

php - fpdf multicell 没有生成相同的高度

php - strpos 不适用于某个字符串

php - 如何使用 strpos 确定输入字符串中是否存在字符串?