Check if a string contains a substring in 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
1 | 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.
1 2 3 4 5 6 7 8 9 10 11 | <?php $mainString = "Welcome to Clue Mediator"; $word = "Clue"; 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.
1 2 3 4 5 6 7 8 9 10 11 12 | <?php $mainString = "Welcome to Clue Mediator"; $word = "Welcome"; 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.
1 2 3 4 5 6 7 8 9 10 11 12 | <?php $mainString = "Welcome to Clue Mediator"; $word = "mediator"; 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..!!