How to check if string contain specific word using str_contains function_
  • February 2, 2025
  • Azad Chouhan
  • 0

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’;
}

In the above case the output will be true because the string “How are you” contains the substring “are”

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!”;
}

The output of the above code always will be “This returned true!” even the $needle is empty. If you want to avoid this situations then always check if the needle is not empty before calling the str_contains. Here is an example of this

$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.

So in this article you learn about the behavior of the str_contains in PHP 8 and  its offer a more simple and readable way to check for substrings as compared to the older strpos method. You can effectively utilize this function to enhance string manipulation in your application.
That’s all for this post. I hope you understand the concept of str_contains function and how to use it. Comment below your thoughts and questions regarding any issue of this topic. You can also email if on co*****@az*********.com. I will revert as soon as possible to your queries.

 

Leave a Reply

Your email address will not be published. Required fields are marked *