PHP str_contains() Function

What is PHP str_contains() Function?

If you want to find whether a string contains a word or group of words in another string, use php str_contains() function.

Syntax:

str_contains(string, sub_string)

Parameters:

The Function has 2 required parameters-

string (Required): It specifies a string where you’ll look for the 2nd parameter (sub string).

sub_string (Optional): It specifies the sub string that you’ll look for in the 1st parameter (string).

Return Values:

The function returns-

  • TRUE – if the sub string found in the string.
  • FALSE – if the sub string not found in the string.

Examples:

Example 1:

<?php
$string = "Learn PHP from Schools of web";
$sub_string = "Schools";
echo str_contains($string, $sub_string) ? "$sub_string found in the string." : "$sub_string not found in the string.";
?>

Output:

Schools found in the string.

Example 2:

<?php
$string = "Learn javascript from Schools of web";
$sub_string = "Javascript";
echo str_contains($string, $sub_string) ? "$sub_string found in the string." : "$sub_string not found in the string.";
?>

Output:

Javascript not found in the string.

Example 3:

<?php
$string = "Learn CSS from Schools of web";
$sub_string = "";
echo str_contains($string, $sub_string) ? "The sub string found in the string." : "The sub string not found in the string.";
?>

Output:

The sub string found in the string.

Notes on str_contains() Function:

  • It matches in case-sensitive manner which means it differentiates capital and small letters. Check example 2.
  • The  function always returns TRUE (meaning found) if the word or substring that you use to search is empty. Check example 3.

PHP Version Support:

PHP 8

Summary: PHP str_contains() Function

str_contains() function is one of the built-in string functions. It is the easiest way to check whether a sub string exists in another string.

Reference:

https://www.php.net/manual/en/function.str-contains.php