To check if a string contains a specific word or substring in PHP, you can use one of the following methods:
1. Using strpos()
(Case-Sensitive Check)
This method checks for the case-sensitive existence of a substring.
$string = "The quick brown fox jumps over the lazy dog";
$word = "fox";
if (strpos($string, $word) !== false) {
echo "The string contains the word '$word'.";
} else {
echo "The string does NOT contain the word '$word'.";
}
Notes:
strpos()
returns the position of the first occurrence of the substring (0
or higher) orfalse
if not found.- Use
!== false
for accurate checks (since0
is a valid position and== false
would incorrectly fail).
2. Using str_contains()
(PHP 8.0+)
Simplifies substring checks with a direct boolean return (case-sensitive).
if (str_contains($string, $word)) {
echo "The string contains '$word'.";
}
3. Case-Insensitive Check
To ignore case, use stripos()
or combine strtolower()
with str_contains()
.
Using stripos()
:
if (stripos($string, "FOX") !== false) {
echo "Case-insensitive match found.";
}
Using str_contains()
with strtolower()
(PHP 8.0+):
if (str_contains(strtolower($string), strtolower($word))) {
echo "Case-insensitive match found.";
}
4. Check for Whole Words (Regex)
Use regular expressions to ensure the substring is a whole word (not part of another word).
if (preg_match('/\b' . preg_quote($word, '/') . '\b/i', $string)) {
echo "Exact word match found (case-insensitive).";
}
Explanation:
\b
marks a word boundary.i
flag makes the search case-insensitive.preg_quote()
escapes special regex characters in$word
.
5. Using strstr()
Checks if a substring exists and returns part of the string (case-sensitive).
if (strstr($string, $word) !== false) {
echo "Substring found.";
}
Summary
Method | Case-Sensitive | Returns | Best For |
---|---|---|---|
strpos() | ✅ Yes | Position/false | General substring checks |
str_contains() | ✅ Yes | true /false | PHP 8.0+ simplicity |
stripos() | ❌ No | Position/false | Case-insensitive checks |
Regex (preg_match ) | Optional | 1 (found)/0 (not) | Complex patterns/whole words |
Best Practice
- For PHP 8.0+: Use
str_contains()
for simplicity. - For older PHP versions: Use
strpos()
with strict!== false
checks. - For case-insensitive checks: Use
stripos()
orstr_contains()
withstrtolower()
. - For whole words: Use regex with
preg_match()
and word boundaries (\b
).
By choosing the right method, you can efficiently check for substrings in PHP!