if (strpos(htmlentities($storage->getMessage($i)),'chocolate'))
Hi, I'm using gmail oauth access to find specific text strings in email addresses. Is there a way to find text instances quicker and more efficiently than using strpos in the above code? Should I be using a hash technique?
strpos is likely to be faster than preg_match and the alternatives in this case, the best idea would be to do some benchmarks of your own with real example data and see what is best for your needs, although that may be overdoing it. Don't worry too much about performance until it starts to become a problem
strpos return the begin position of first occurence of string, if no match will return Null so statement is fairly usable.
According to the PHP manual, yes-
strpos()
is the quickest way to determine if one string contains another.This is quoted time and again in any php.net article about other string comparators (I pulled this one from
strstr()
)Although there are two changes that should be made to your statement.
This is because
if(0)
evaluates to false (and therefore doesn't run), howeverstrpos()
can return 0 if the needle is at the very beginning (position 0) of the haystack. Also, removinghtmlentities()
will make your code run a lot faster. All thathtmlentities()
does is replace certain characters with their appropriate HTML equivalent. For instance, it replaces every&
with&
As you can imagine, checking every character in a string individually and replacing many of them takes extra memory and processor power. Not only that, but it's unnecessary if you plan on just doing a text comparison. For instance, compare the following statements:
Or, in the worst case, you may even cause something true to evaluate to false.
In order to circumvent this you'd end up using even more HTML entities.
But this, as you can imagine, is not only annoying to code but gets redundant. You're better off excluding HTML entities entirely. Usually HTML entities is only used when you're outputting text. Not comparing.