preg_match() vs strpos() 进行匹配查找?

php
2022-08-30 13:16:41

对于单值检查,两者中哪一个是首选,为什么?

$string == 'The quick brown fox jumps over the lazy dog';

if(strpos($string, 'fox') !== false){
    // do the routine
}

# versus

if(preg_match('/fox/i', $string)){
    // do the routine
}

答案 1

我更喜欢,因为正则表达式的执行成本通常更高。strpospreg_match

根据官方的php文档preg_match

如果您只想检查一个字符串是否包含在另一个字符串中,请不要使用。使用或代替,因为它们会更快。preg_match()strpos()strstr()


答案 2

如有疑问,请进行基准测试!

显然,我们本可以提出一个比这更好的基准,但只是为了证明这一点,随着它开始扩大规模,它将会快得多。(这里快了2倍)strpos()

编辑后来我注意到正则表达式不区分大小写。当再次使用更公平的比较来运行它时,结果是11到15,因此差距缩小但保持慢得多。stripos()preg_match()

$str = "the quick brown fox";
$start1 = time();
for ($i = 0; $i<10000000; $i++)
{
    if (strpos($str, 'fox') !== false)
    {
        //
    }
}
$end1 = time();
echo $end1 - $start1 . "\n";

$start2 = time();
for ($i = 0; $i<10000000; $i++)
{
    if (preg_match('/fox/i', $str))
    {
        //
    }
}
$end2 = time();
echo $end2 - $start2;

// Results:
strpos() = 8sec
preg_match() = 15sec

// Results both case-insensitive (stripos()):
stripos() = 11sec
preg_match() = 15sec

推荐