
Developer can access to the new function str_contains after the release of PHP 8. This function helps to check weather a substring exists within a larger string. For example if you wat to check word “are” in the string How are you? then you can use this particular function. In this article we will discuss how to use the str_contains and its behavior with empty strings, case sensitivity
Use of str_contains function
The str_contains function provides simple way to check if a substring exists within a string. Let go through the following code snippet for example
if (str_contains(‘How are you’, ‘are’)) {
echo ‘true’;
}
How to handle the empty substring with str_contains function ?
One important point about str_contains is its behavior when the $needle is empty string. The function always return true if the $needle is empty. this behavior can lead to unexpected results if its not handled property. Below is the example of this
$haystack = ‘Hello’;
$needle = ”;if (str_contains($haystack, $needle)) {
echo “This returned true!”;
}
$haystack = ‘How are you?’;
$needle = ”;if ($needle !== ” && str_contains($haystack, $needle)) {
echo “This returned true!”;
} else {
echo “This returned false!”;
}
and in the above code now the output will be “This returned false!”;
str_contains is case sensitive
Another feature of str_contains is that it is case- sensitive . This function never handle upper case and lower case letters in same way. First of all check the following code
$haystack = ‘How are you?’;
$needle = ‘how’;if ($needle !== ” && str_contains($haystack, $needle)) {
echo “This returned true!”;
} else {
echo “This returned false!”;
}
Above code return “This returned false!” because the $needle value is in lowercase and $haystack “How” contains uppercase letter.