PHP to check substring in a string

To check substring in a string, the code is as follows in PHP −

Example

<?php
   $subStr = "Mother";
   $str = "How I Met Your Mother";
   echo "String = $str";
   echo "\nSubstring = $subStr";
   if(strpos($str, $subStr) !== false){
      echo "\nSubstring found successfully";
   } else{
      echo "\nSubstring not found";
   }
?>

Output

This will produce the following output−

String = How I Met Your Mother
Substring = Mother
Substring found successfully

Example

Let us now see another example −

<?php
   $subStr = "Ocean";
   $str = "In the Heart of Sea";
   echo "String = $str";
   echo "\nSubstring = $subStr";
   if(strpos($str, $subStr) !== false){
      echo "\nSubstring found successfully";
   } else{
      echo "\nSubstring not found";
   }
?>

Output

This will produce the following output−

String = In the Heart of Sea
Substring = Ocean
Substring not found
Updated on: 2026-03-11T22:50:47+05:30

285 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements