php preg_match() 与 strpos() 用于匹配查找?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6433492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
preg_match() vs strpos() for match finding?
提问by jolt
For single value check, which of both is preferred and why?
对于单值检查,两者中的哪一个是首选,为什么?
$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
}
回答by
I would prefer the strpos
over preg_match
, because regexes are generally more expensive to execute.
我更喜欢strpos
over preg_match
,因为执行正则表达式通常更昂贵。
According to the official php docs for preg_match
:
根据官方 php 文档preg_match
:
Do not use
preg_match()
if you only want to check if one string is contained in another string. Usestrpos()
orstrstr()
instead as they will be faster.
preg_match()
如果您只想检查一个字符串是否包含在另一个字符串中,请不要使用。使用strpos()
orstrstr()
代替,因为它们会更快。
回答by Michael Berkowski
When in doubt, benchmark!
如有疑问,请进行基准测试!
Obviously we could have come up with a better benchmark than this, but just to prove the point that as it starts to scale up, strpos()
is going to be quite a bit faster. (almost 2x as fast here)
显然,我们可以想出比这更好的基准,但只是为了证明这一点,当它开始扩大规模时,strpos()
速度会快很多。(这里几乎快 2 倍)
EDITI later noticed that the regex was case-insensitive. When running this again using stripos()
for a more fair comparison, the result is 11 to 15, so the gap narrows but preg_match()
remains a lot slower.
编辑我后来注意到正则表达式不区分大小写。再次运行stripos()
以进行更公平的比较时,结果是 11 到 15,因此差距缩小但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
回答by glortho
Never use regular expressions unless absolutely necessary. The overhead involved in starting up and deploying the regex engine on a string like this is similar to using a Hymanhammer instead of a regular hammer, a drill instead of a screwdriver.
除非绝对必要,否则不要使用正则表达式。在像这样的字符串上启动和部署正则表达式引擎所涉及的开销类似于使用手提钻代替普通锤子、使用钻头代替螺丝刀。
You also have a greater margin of error with regex – mismatched strings, unexpected results, etc. Stick with strpos unless strpos isn't flexible enough.
使用正则表达式也有更大的误差范围——不匹配的字符串、意外的结果等。坚持使用 strpos,除非 strpos 不够灵活。
回答by ZJR
If you're already using preg_match
and preg_replace
all over the place in your code, then go on and use it once more. Why?
如果您已经使用preg_match
并preg_replace
在所有在你的代码的地方,然后再上,并再次使用它。为什么?
Performance.Most of the overhead those function add is in the initial load time of the engine, if you already paid that price, make it worth it.
Readability.
strpos(...)!==false
, while faster, is an incredibile eyesore.It is one of the ugliestphp constructs.
The usage of==
andfalse
in it are really kludgy and look hard to parse and frail to edit.
表现。这些函数添加的大部分开销都在引擎的初始加载时间,如果您已经付出了这个代价,那就值得了。
可读性。
strpos(...)!==false
虽然速度更快,但令人难以置信。它是最丑陋的php 结构之一。
其中==
和 的用法false
非常笨拙,看起来难以解析且难以编辑。
Shame on the core team for not having defined an alias like strcontains()
for it, years ago.
Now it's well too lateto do that, but it would have been nice, back then.
strcontains()
多年前,核心团队没有为它定义一个别名,这让他们感到羞耻。
现在这样做已经太晚了,但在那时会很好。
回答by Mike Q
So if anyone thinks this type of thing is of any importance, should take note that it's a constant in Big O. In other words, database calls, On^2 or worse activity is all that matters. Taking the time to fret over these low level commands is pointless in most usage. Not saying that constants should be ignored, for example, I refactored code that grabbed images because it did it one at a time taking 1sec each, where it reduced it from 12 secs to 1 sec (using multi curl request). The point is that built in commands are lower level, the code structure is more important.
所以如果有人认为这种类型的事情有任何重要性,应该注意它在 Big O 中是一个常数。换句话说,数据库调用、On^2 或更糟的活动才是最重要的。在大多数情况下,花时间为这些低级命令烦恼是没有意义的。并不是说常量应该被忽略,例如,我重构了抓取图像的代码,因为它一次执行一次,每次需要 1 秒,将其从 12 秒减少到 1 秒(使用多卷曲请求)。重点是内置命令级别较低,代码结构更重要。
The code below is 10Million calls, and the "savings" is nearly nothing.
下面的代码是1000万次调用,“节省”几乎为零。
function prof_flag($str)
{
global $prof_timing, $prof_names;
$prof_timing[] = microtime(true);
$prof_names[] = $str;
}
function prof_print()
{
global $prof_timing, $prof_names;
$size = count($prof_timing);
for($i=0;$i<$size - 1; $i++)
{
echo "<b>{$prof_names[$i]}</b><br>";
echo sprintf(" %f<br>", $prof_timing[$i+1]-$prof_timing[$i]);
}
echo "<b>{$prof_names[$size-1]}</b><br>";
}
$l = 10000000;
$str = "the quick brown fox";
echo "<h3>Ran " .number_format($l,2) ." calls per command </h3>";
prof_flag("Start: stripos");
for ($i = 0; $i<$l; $i++)
if (stripos($str, 'fox') !== false) {}
prof_flag("Start: preg_match");
for ($i = 0; $i<$l; $i++)
if (preg_match('#fox#i', $str) === 1) {}
prof_flag("Finished");
prof_print();
Only value to this code is that it shows a cool way to record times things take to run lol
这段代码的唯一价值是它显示了一种很酷的方式来记录运行所需的时间 lol
Ran 10,000,000.00 calls per command
Start: stripos
2.217225
Start: preg_match
3.788667
Start: ==
0.511315
Start: ucwords lol
2.112984
Finished
回答by asdkhasd
You can optimize the above preg_match
by writing :
您可以preg_match
通过编写以下内容来优化上述内容:
preg_match('/(?>fox)/', $str)
this should be more faster.
这应该更快。