How to check if a string contains a substring in PHP?
From PHP 8 use str_contains(). It returns true or false. In older versions use strpos(), which returns the position of the match or false.
<?php
$text = "Hello world!";
var_dump(str_contains($text, "world"));
var_dump(strpos($text, "Hello"));
?>
Output:
Tutorials Class - Output Window
bool(true)
int(0)
Look at the second result. The word “Hello” is at position 0, and 0 is also treated as false in a normal comparison. This is the most common mistake with strpos(), so always compare with !==.
<?php
$text = "Hello world!";
if (strpos($text, "Hello") == false) {
echo "Wrong: says not found<br>";
}
if (strpos($text, "Hello") !== false) {
echo "Correct: found";
}
?>
Output:
Tutorials Class - Output Window
Wrong: says not found
Correct: found
Both functions are case-sensitive. Learn more in PHP strpos() Function.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |