Skip to content
Advertisement

How do I check if a string contains a specific word?

Consider:

JavaScript

Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are')?

Advertisement

Answer

Now with PHP 8 you can do this using str_contains:

JavaScript

RFC

Before PHP 8

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

JavaScript

Note that the use of !== false is deliberate (neither != false nor === true will return the desired result); 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').

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement