PHP 8 – Using str_contains() to check if a string contains a substring


In PHP 8, str_contains function determines if a string contains a given substring anywhere. The str_contains function checks if a first-string is contained in the second string and it returns a true /false Boolean value based on whether the string is found or not. it is a self-explanatory function.

str_contains(string $haystack, string $needle): bool

Example1 : PHP 8 str_contains function.

<?php
   if (str_contains('great reading tutorial', 'tutorial')) {
      var_dump('Tutorial has been found');
   }
?>

Output

string(23) "Tutorial has been found"

Example: str_contains function.

<?php
   if (str_contains('great reading tutorial', 'hello')){
      var_dump('great reading');
   }
?>

Note: The above program returns false because the first string does not contain the second string.

strpos() function

In PHP 7.x, strops() function is used to check if a given string contains another string or not. This function returns the position of the needle string, or it returns false if the string needle is not found.

if (strpos('string with lots of words', 'words') !== false) { /* … */ }

Example: PHP 7.x strops() function

 Live Demo

<?php
   $string = 'Hello World!';
   if (strpos($string, 'Hello') !== false) {
      echo 'True';
   }
?>

Output

True

Updated on: 01-Apr-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements