Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP to check substring in a string
In PHP, you can check if a substring exists within a string using the strpos() function. This function returns the position of the first occurrence of a substring, or false if not found.
Using strpos() Function
The strpos() function is case-sensitive and returns the numeric position of the substring or false if not found ?
<?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";
}
?>
String = How I Met Your Mother Substring = Mother Substring found successfully
Example with Substring Not Found
Here's an example where the substring is not present in the string ?
<?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";
}
?>
String = In the Heart of Sea Substring = Ocean Substring not found
Important Note
Always use the strict comparison operator !== when checking strpos() results, because if the substring is found at position 0, it returns 0 which evaluates to false in loose comparison.
Conclusion
The strpos() function is the most efficient way to check if a substring exists in a string. Remember to use strict comparison (!==) to avoid false negatives when the substring appears at the beginning of the string.
