How to check if a String Contains a Substring in PHP ?
Last Updated :
06 May, 2025
Improve
Checking whether a string contains a specific substring is a common task in PHP. Whether you're parsing user input, filtering content, or building search functionality, substring checking plays a crucial role.
Methods
Below are the following methods by which we can check if a string contains a substring in PHP:
1. Using str_contains()
(PHP 8+)
<?php
$text = "Welcome to Empowerfit!";
if (str_contains($text, "Empower")) {
echo "Substring found!";
} else {
echo "Substring not found.";
}
?>
Output:
Substring found!
2. Using strpos() (All PHP versions)
<?php
$text = "Learn PHP programming";
if (strpos($text, "PHP") !== false) {
echo "Substring found!";
} else {
echo "Substring not found.";
}
?>
Output:
Substring found!
3. Case-Insensitive Search with stripos()
<?php
$text = "Power of Coding";
if (stripos($text, "power") !== false) {
echo "Substring found (case-insensitive)!";
}
?>
Output:
Substring found (case-insensitive)!
4. Using Regular Expressions with preg_match()
<?php
$text = "Develop with PHP";
if (preg_match("/PHP/", $text)) {
echo "Match found using regex.";
}
?>
Best Practices
- Use
str_contains()
for simple checks (if PHP 8+). - Always check
strpos
with!== false
, not!= false
. - Use
stripos()
for case-insensitive searches. - Prefer
preg_match()
only for complex pattern matching.