I noticed a lot of developers are using both strstr and strpos to check for a substring existence. Is one of them preferred and why ?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
From the PHP online manual:
I prefer
strstr()
for readability and easy coding..strpos() !==false
is confusing a bit..Many developers use
strpos
for micro optimization purposes.Using
strstr
also only works if the resulting string cannot be interpreted as false in boolean context.Here are some other answers (+benchmarks) I got to my question, which is almost the same (I didn't realize yours when asking).
In the meantime I also made my own benchmark test, which I ran 1000000 times for each relevant functions (
strstr()
,strpos()
,stristr()
andstripos()
).Here's the code:
And here is the first output, which shows that
strpos()
is the winner:The next one is similar to the first output (
strpos()
is the winner again):Below is another one, which is more interesting, because in this case,
strstr()
is the winner:This means it can really depend on "environmental circumstances", which are sometimes hard to influence, and can change the result of "micro optimization tasks" like this, in case you are just checking whether a string exists in another one or not.
BUT I think in most cases,
strpos()
is the winner in comparison tostrstr()
.I hope this test was useful for someone.
strpos() detects where in the haystack a particular needle lies. stristr() tests whether the needle is anywhere in the haystack
therefor strpos() is faster and less memory consuming
a reason for strstr(): if your needle is at the beginning of a string, strpos returns 0 (so have to check it with === false)