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')
?
Using
strstr()
orstristr()
if your search should be case insensitive would be another option.I had some trouble with this, and finally I chose to create my own solution. Without using regular expression engine:
You may notice that the previous solutions are not an answer for the word being used as a prefix for another. In order to use your example:
With the samples above, both
$a
and$b
contains$c
, but you may want your function to tell you that only$a
contains$c
.Another option to finding the occurrence of a word from a string using strstr() and stristr() is like the following:
You need to use identical/not identical operators because strpos can return 0 as it's index value. If you like ternary operators, consider using the following (seems a little backwards I'll admit):
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. (http://in2.php.net/preg_match)You should use case Insensitive format,so if the entered value is in
small
orcaps
it wont matter.Here stripos finds needle in heystack without considering case (small/caps).
PHPCode Sample with output