Consider:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are')
?
Consider:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are')
?
Make use of case-insensitve matching using
stripos()
:In PHP, the best way to verify if a string contains a certain substring, is to use a simple helper function like this:
Explanation:
strpos
finds the position of the first occurrence of a case-sensitive substring in a string.stripos
finds the position of the first occurrence of a case-insensitive substring in a string.myFunction($haystack, $needle) === FALSE ? FALSE : TRUE
ensures thatmyFunction
always returns a boolean and fixes unexpected behavior when the index of the substring is 0.$caseSensitive ? A : B
selects eitherstrpos
orstripos
to do the work, depending on the value of$caseSensitive
.Output:
If you want to check if the string contains several specifics words, you can do:
This is useful to avoid spam when sending emails for example.
You could use regular expressions, it's better for word matching compared to strpos as mentioned by other users it will also return true for strings such as fare, care, stare etc. This can simply be avoided in the regular expression by using word boundaries.
A simple match for are could look something like this:
On the performance side, strpos is about three times faster and have in mind, when I did one million compares at once, it took
preg_match
1.5 seconds to finish and for strpos it took 0.5 seconds.This means the string has to be resolved into words (see note below).
One way to do this and to specify the separators is using
preg_split
(doc):A run gives
Note: Here we do not mean word for every sequence of symbols.
A practical definition of word is in the sense the PCRE regular expression engine, where words are substrings consisting of word characters only, being separated by non-word characters.
You can use the
strpos()
function which is used to find the occurrence of one string inside another one:Note that the use of
!== false
is deliberate;strpos()
returns either the offset at which the needle string begins in the haystack string, or the booleanfalse
if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like!strpos($a, 'are')
.