How to Check if String Contains Substring in PHP
In PHP, you can check if a string contains a substring using the
strpos() function. It returns the position of the substring or false if not found, so check with strict comparison !== false to confirm presence.Syntax
The strpos() function searches for the first occurrence of a substring inside a string.
haystack: The main string to search in.needle: The substring to find.- Returns the position (0-based index) if found, or
falseif not found.
Use strict comparison !== false to check if substring exists because position 0 is valid.
php
int|false strpos(string $haystack, string $needle)
Example
This example shows how to check if the word "world" is inside the string "Hello world!" and prints a message accordingly.
php
<?php $text = "Hello world!"; $search = "world"; if (strpos($text, $search) !== false) { echo "Found '$search' in the text."; } else { echo "Did not find '$search' in the text."; }
Output
Found 'world' in the text.
Common Pitfalls
A common mistake is to check if (strpos(...) == false) which fails when the substring is at position 0 (start of string). Always use strict comparison !== false.
php
<?php // Wrong way $text = "hello"; if (strpos($text, "he") == false) { echo "Not found (wrong check)."; } else { echo "Found (wrong check)."; } // Right way if (strpos($text, "he") !== false) { echo "Found (correct check)."; } else { echo "Not found (correct check)."; }
Output
Not found (wrong check).Found (correct check).
Quick Reference
Remember these tips when checking substrings in PHP:
- Use
strpos()to find substring position. - Check with
!== falseto confirm substring exists. - Substring at start returns 0, which is
falsein loose comparison. - Use
stripos()for case-insensitive search.
Key Takeaways
Use strpos() to check if a substring exists in a string in PHP.
Always compare strpos() result with !== false to avoid errors when substring is at position 0.
strpos() returns the position of the substring or false if not found.
Use stripos() for case-insensitive substring checks.
Avoid loose comparison (== false) when checking strpos() results.