PHP Function Reference

PHP str_contains() Function



The PHP str_contains() function is used to check if a string contains a given substring. It performs case-sensitive check and returns true if the string contains specified substring, else returns false.

Note: It is a binary-safe function. This function is new in PHP 8.

Syntax

str_contains(str1, str2)

Parameters

str1 Required. Specify the string to search in.
str2 Required. Specify the substring to search in str1.

Return Value

Returns true if str1 contains str2, else returns false.

Example:

In the example below shows the usage of str_contains() function.

<?php
$str = "Hello";

//checking whether $str contains empty string
if(str_contains($str, "")) {
  echo "Checking for empty string always returns true.\n";
}

//checking whether $str contains "ll"
if(str_contains($str, "ll")) {
  echo "$str contains 'll'.\n";
}
?>

The output of the above code will be:

Checking for empty string always returns true.
Hello contains 'll'.

Example:

Consider one more example which illustrates on case-sensitive check using str_contains() function.

<?php
$str = "Hello John";

//checking whether $str contains "JOHN"
if(str_contains($str, "JOHN")) {
  echo '"JOHN" is found in the string.';
} else {
  echo '"JOHN" is not found because case does not match.';
}
?>

The output of the above code will be:

"JOHN" is not found because case does not match.

❮ PHP String Reference