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')?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Now with PHP 8 you can do this using str_contains:
Please note: The
str_containsfunction will always return true if the $needle (the substring to search for in your string) is empty.You should first make sure the $needle (your substring) is not empty.
Output:
This returned false!It’s also worth noting that the new
str_containsfunction is case-sensitive.Output:
This returned false!RFC
Before PHP 8
You can use the
strpos()function which is used to find the occurrence of one string inside another one:Note that the use of
!== falseis deliberate (neither!= falsenor=== truewill return the desired result);strpos()returns either the offset at which the needle string begins in the haystack string, or the booleanfalseif 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').