In this sample code:
How to write the statement in a proper way
If ($a contains ‘are’)?
- The strpos (http://php.net/manual/en/function).strpos. php function is used to find the occurrence of one string inside other:
The usage of !== false is deliberate; strpos returns either the offset at which the needle string begins in the haystack string, or the Boolean false 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, ‘hello’).
- Here is the another function to check whether the string contains specific word in php.
- To determine whether a string contains another string Here is the another way of using PHP function strpos().
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
- If the needle function given in the beginning of the haystack it will return position 0, if we compare
a == compare then it won’t work,we 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 / expressions / constants are equal and have the same type – i.e. both are strings or both are integers.
- Here is the another way of using strpos() function:
- Use case-insensitve matching using stripos():
- To avoid “falsey” and “truthy” problem, use substr_count:
- Compare to strpos it’s a bit slower only, but this function avoids the comparison problems.
- Here is the another new function called strstr() function. The sample code is given below:
The strstr() function is case-sensitive. For a case-insensitive search, use the stristr() (http://www.php.net/manual/en/function.stristr.php) function.
- Don’t use preg_match() for every cases, In some cases like if we need to check whether one string is contained in another string use strpos() or strstr() instead of preg_match()
- The strpos() or strstr() functions are faster than preg_match()(http://in2.php.net/preg_match)
It can be done in three different ways:
- If we need to check if the string contains several specifics words, Simply use the below code: