Solution for : How do we check if a string contains a specific word in PHP?
We can use the strpos()
function which is used to find the occurrence of one string inside another one:
$a = 'How are you?'; if (strpos($a, 'are') !== false) { echo 'true'; }
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 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, 'are')
.
No comments:
Post a Comment