PHP str_contains
Summary: in this tutorial, you’ll learn how to use the PHP str_contains()
function to check if a string contains a substring.
Introduction to the PHP str_contains() function
The PHP str_contains()
function checks if a string contains a substring. Here’s the syntax of the str_contains()
function:
str_contains ( string $haystack , string $needle ) : bool
Code language: PHP (php)
The str_contains()
function has the following parameters:
$haystack
is the string to be checked.$needle
is the substring to search for in the input string$haystack
.
The str_contains()
function returns true
if the $needle
is in the $haystack
, false
otherwise.
When searching for the $needle
in the $haystack
, the str_contains()
function uses a case-sensitive search.
Note that str_contains()
function has been available since PHP 8.0.0. If you use an earlier version of PHP, you can polyfill the str_contains()
function like this:
if (!function_exists('str_contains')) {
function str_contains( $haystack, $needle)
{
return $needle !== '' && mb_strpos($haystack, $needle) !== false;
}
Code language: PHP (php)
PHP str_contains() function examples
The following example uses the str_contains()
function to check if the string 'PHP'
is in the string 'PHP string functions'
:
$haystack = 'PHP is cool.';
$needle = 'PHP';
$result = str_contains($haystack, $needle) ? 'is' : 'is not';
echo "The string {$needle} {$result} in the sentence.";
Code language: PHP (php)
Output:
The string PHP is in the sentence
Code language: PHP (php)
As mentioned earlier, the str_contains()
function uses the case-sensitive search for checking if a substring is in a string. For example:
$haystack = 'PHP is cool.';
$needle = 'Cool';
$result = str_contains($haystack, $needle) ? 'is' : 'is not';
echo "The string {$needle} {$result} in the sentence.";
Code language: PHP (php)
Output:
The string Cool is not in the sentence.
Code language: PHP (php)
Summary
- Use the PHP
str_contains()
function to carry a case-sensitive search to check if a string is in another string.