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')
?
The short-hand version
Another option is to use the strstr() function. Something like:
Point to note: The strstr() function is case-sensitive. For a case-insensitive search, use the stristr() function.
A string can be checked with the below function:
To determine whether a string contains another string you can use the PHP function strpos().
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
CAUTION:
If the needle you are searching for is at the beginning of the haystack it will return position 0, if you do a
==
compare that will not work, you will need to do a===
A
==
sign is a comparison and tests whether the variable / expression / constant to the left has the same value as the variable / expression / constant to the right.A
===
sign is a comparison to see whether two variables / expresions / constants are equalAND
have the same type - i.e. both are strings or both are integers.If you want to avoid the "falsey" and "truthy" problem, you can use substr_count:
It's a bit slower than strpos but it avoids the comparison problems.
It can be done in three different ways:
1- stristr()
2- strpos()
3- preg_match()