Avatar
7718 reputation
Posted on:24 Aug '16 - 10:37
150

Check if string contains specific words?

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')

PHP

Answers

175
This answer is accepted

You can use the strpos function which is used to find the occurrence of one string inside other:

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').

Avatar
11977 reputation
Posted on:25 Aug '16 - 05:37

Please login in order to answer a question