Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP String str_contains() Function



The PHP String str_contains() function is a built-in function introduced with the release of PHP 8. This function looks for a substring within the given string using the expression. If the given substring exists in the string, it returns True; otherwise, it returns False. The str_contains() function is very similar to strpos() function.

Syntax

Below is the syntax of the PHP String str_contains() function −

bool str_contains(string $string, string $search )

Parameters

Here are the parameters of the str_contains() function −

  • $string − (Required) It is the string to search in.

  • $search − (Required) It is the substring to search for in the $string.

Return Value

The str_contains() function returns TRUE if needle is in $string, FALSE otherwise.

PHP Version

This function is introduced with the release of PHP 8.

Example 1

Here is the basic example of the PHP String str_contains() function to check if "world" exists in "Hello world!".

<?php
   // Define the string here
   $string = "Hello world!";
   $search = "world";

   echo str_contains($string, $search);
?>

Output

Here is the outcome of the following code −

1

Example 2

In the below PHP code, we will use the str_contains() function and see the case sensitivity of this function.

<?php
   // Define the string here
   $string = "Welcome to PHP Tutorials!";
   $search = "php";

   if (str_contains($string, $search)) {
      echo "The string contains '$search'.";
   } else {
      echo "The string does not contain '$search'.";
   }
?> 

Output

This will generate the below output −

The string does not contain 'php'.

Example 3

Now the below code uses the str_contains() function to check multiple substrings in a single string. So the code iterates over an array of substrings and checks each one in the main string.

<?php
   // Define the string here
   $string = "PHP is a popular scripting language for web development.";
   $searchTerms = ["PHP", "scripting", "JavaScript", "web"];

   foreach ($searchTerms as $term) {
      if (str_contains($string, $term)) {
         echo "The string contains '$term'.\n";
      } else {
         echo "The string does not contain '$term'.\n";
      }
   }
?> 

Output

This will create the below output −

The string contains 'PHP'.
The string contains 'scripting'.
The string does not contain 'JavaScript'.
The string contains 'web'.
php_function_reference.htm
Advertisements