Last updated on May 5, 2023
The str_contains() function searches the string into another, or for easy understanding, it searches a word, letter or phrase in the sentence. It returns Boolean, so the response will always be either true or false. It is introduced in PHP version 8.
Syntax:
str_contains(string $string, string $substring);
Parameters:
Detail:
Example 1:
Let’s understand it by an example.
$response = str_contains("iphone", "e");
var_dump($response);
// Output: bool(true)
In this example, we have a string in which we need to check if it contains the alphabet letter “e”. To do that, we passed the “iphone” string as the first argument and the “e” string as the second argument into the str_contains()
function. In the response we got a Boolean value true, which is because the alphabet letter “e” exists in the iphone string.
The str_contains()
has the ability to check case sensitivity of the value. Let’s test it by capitalizing the alphabet letter “e”.
$response = str_contains("iphone", "E");
var_dump($response);
// Output: bool(false)
As you can see, we passed the capital alphabet letter “E” and in the response we got a false value which means str_contains()
searches value in the string with case sensitivity.
Example 2:
In this example, we will be searching for a word in the sentence using the str_contains()
function.
$sentence = "Coder Advice aims to provide best tutorials.";
$response = str_contains($sentence, "best");
var_dump($response);
// Output: bool(true)
In the above script, the str_contains()
function checks if the string value “best” exists in the provided sentence. In the response, the function returns true because the “best” string exists in the sentence and also case sensitivity of the value matches with the value that str_contains()
found in the sentence.
Comparison with strpos() function
Some of you might interested to know about the difference between the strpos() function and str_contains() function. The strpos() function finds the first position of the substring within the string, while str_contains() function searches the string into another.
Moreover, strpos() returns false when it fails to find the substring and in case of success it returns the integer value. While, the str_contains() function returns Boolean (true, false).
Conclusion
This article demonstrates how can you search substring into a string using PHP’s built-in function str_contains(). It accepts two parameters which first is a string and the second is a substring and it returns Boolean.