Open In App

How to check if a String Contains a Substring in PHP ?

A string is a collection of given characters and a substring is a string present in a given string.

In this article, we are going to check if the given string contains a substring by using the PHP strpos() function.



Syntax:

strpos($original_string,$sub_string);

Parameters:



Return type: Boolean value

Example:




<?php
//input string
$input_string = "sravan kumar author at geeks for geeks ";
  
//sub string to be checked
$sub = "geeks";
  
// Test if string contains the word
if (strpos($input_string, $sub) !== false)
{
    echo "True";
}
else
{
    echo "False";
}
?>

Output:

True

Example 2:




<?php
//input string
$input_string = "sravan kumar author at geeks for geeks ";
  
//sub string to be checked
$sub = "computer";
  
// Test if string contains the word
if (strpos($input_string, $sub) !== false)
{
    echo "True";
}
else
{
    echo "False";
}
?>

Output:

False

Example 3: The following example also considers space.




<?php
//input string
$input_string = "geeks for geeks java python php";
  
//sub string to be checked
$sub = " ";
  
// Test if string contains the word
if (strpos($input_string, $sub) !== false)
{
    echo "True";
}
else
{
    echo "False";
}
?>

Output:

True

Example 4:




<?php
//input string
$input_string = "geeks for geeks java python php";
  
//sub string to be checked
$sub = " dbms";
  
// Test if string contains the word
if (strpos($input_string, $sub) !== false)
{
    echo "True";
}
else
{
    echo "False";
}
?>

Output:

False

Article Tags :