Clue Mediator

Check if a string contains a substring in PHP

📅November 8, 2020
🗁PHP

Today we’ll explain to you how to check if a string contains a substring in PHP. Using PHP in-built `strpos()` function, we can easily check whether a string contains substring or not.

The strpos() function returns the position of the first appearance of a substring in a string. If the substring is not found then it returns the `false`.

Note: The `strpos()` function check string positions start at 0, and not 1.

Syntax

strpos( $string, $substring )

Parameters

  • $string: This parameter specifies the original string in which we need to find the substring.
  • $substring: It specifies the substring which we need to search.

Let’s take examples for better understanding.

Example 1

The following code returns the `true` value because the main string contains the substring.

<!--?php
$mainString = "Welcome to Clue Mediator";
$word = "Clue";<p-->

if(strpos($mainString, $word) !== false){
    echo  "The word ".$word." found.";
} else{
    echo "The word ".$word." not found.";
}
?>
//Output: The word Clue found.

Example 2

In another example, we will check if a string contains a substring at the beginning.

<!--?php
$mainString = "Welcome to Clue Mediator";
$word = "Welcome";<p-->

if(strpos($mainString, $word) === 0){
    echo "The word ". $word." found at the beginning.";
} else{
    echo "The word ".$word." not found at the beginning.";
}
?>

//Output: The word Welcome found at the beginning.

Example 3

The `strpos()` function is case-sensitive. So, you can use the `stripos()` function which is case-insensitive which checks the uppercase and lowercase equally.

<!--?php
$mainString = "Welcome to Clue Mediator";
$word = "mediator";<p-->

if(stripos($mainString, $word) !== false){
    echo  "The word ".$word." found.";
} else{
    echo "The word ".$word." not found.";
}
?>

//Output: The word mediator found.

That’s it for today.
Thank you for reading. Happy Coding..!!