Open In App

PHP str_contains() Function

Last Updated : 09 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The str_contains() is a predefined function that is introduced with the release of PHP 8. The str_contains() function search for the substring in the given string within the expression. If the substring mentioned will be present in the string then it will return True otherwise it will return False. The str_contains() function is very similar to strpos() function.

Properties: 

  1. It always returns a boolean value.
  2. It will return TRUE in case of checking for the substring as empty.
  3. It is case-sensitive.
  4. This function is binary-safe.
  5. It is only supported on PHP 8 or higher versions.

Syntax:

(str_contains('String', 'Substring')) ;

A substring is a string that needs to be searched whereas a string is a part where a substring is to be searched.

Note: str_contains() is only supported in PHP 8 or higher versions.

Example: In the below example, we have a sentence stored in $sentence and a word stored in $word. In this example, we are trying to check whether the word is present in the sentence or not by using the str_contains() function. If the word will be present in the sentence ‘is’ will be assigned to $result otherwise its value will be ‘is not‘. We will understand this using example.

PHP




<?php
 
$sentence = 'GFG is Awesome';
$word = 'GFG';
 
$result = str_contains($sentence, $word) ? 'is' : 'is not';
 
echo "The word {$word} {$result} present in the sentence \"{$sentence}\" ";
 
?>


From the above, we have seen how to find the substring in a given string by using the str_contains() function & the return value will be the boolean. 

Output:

The word GFG is present in the sentence "GFG is Awesome"

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads