Question
I have a PHP string and want to check whether it contains a specific word.
$a = 'How are you?';
if ($a contains 'are') {
echo 'true';
}
What is the correct way to write the condition that checks whether $a contains 'are'?
Short Answer
By the end of this page, you will understand how to check whether a string contains another string in PHP, when to use strpos() or str_contains(), how to handle edge cases correctly, and which beginner mistakes to avoid.
Concept
In PHP, there is no special keyword like contains for strings. To check whether one string appears inside another, you use a string-search function.
The two most common options are:
strpos()— works in older and modern PHP versionsstr_contains()— simpler and clearer, available in newer PHP versions
This matters because checking for text inside strings is extremely common in programming. You might need to:
- validate user input
- search log messages
- detect keywords in text
- filter data from files or APIs
- route requests based on URL content
A very important detail is that strpos() returns the position where the text starts, not just true or false.
For example, if the substring is found at the beginning of a string, strpos() returns 0. Since 0 is treated as falsey in PHP, many beginners accidentally write incorrect checks.
That is why this is correct:
if (strpos($a, 'are') !== false) {
echo 'true';
}
And this is wrong:
if (strpos($a, 'are')) {
echo 'true';
}
If you are using PHP 8+, str_contains() is usually easier to read:
if (str_contains($a, 'are')) {
echo 'true';
}
So the core concept is: use a string-search function, and understand what it returns.
Mental Model
Think of a string as a long sentence written on a strip of paper.
- The main string is the full strip:
'How are you?' - The word you are searching for is a smaller piece:
'are'
PHP scans the strip from left to right looking for that smaller piece.
With strpos(), PHP tells you where it found the match:
0means it starts at the first character4means it starts at the fifth characterfalsemeans it was not found at all
With str_contains(), PHP gives a simpler answer:
trueif foundfalseif not found
So:
strpos()answers: Where is it?str_contains()answers: Is it there?
Syntax and Examples
Using strpos()
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
Explanation
strpos($a, 'are')searches for'are'inside$a- If found, it returns the starting index
- If not found, it returns
false !== falseis required so that position0is not confused withfalse
Using str_contains() in PHP 8+
$a = 'How are you?';
if (str_contains($a, 'are')) {
echo 'true';
}
Explanation
str_contains()directly returnstrueorfalse- It is easier to read when you only care whether the substring exists
Example: substring at the beginning
$a = 'apple pie';
if (strpos($a, 'apple') !== false) {
echo 'Found';
}
This prints Found because 'apple' starts at index 0.
Example: case-sensitive search
$a = 'How are you?';
var_dump(str_contains($a, 'Are')); // false
var_dump(str_contains($a, 'are')); // true
String searches in PHP are case-sensitive unless you intentionally use a case-insensitive approach.
Step by Step Execution
Consider this code:
$a = 'How are you?';
$result = strpos($a, 'are');
if ($result !== false) {
echo 'true';
} else {
echo 'false';
}
Step-by-step
$ais assigned the string'How are you?'strpos($a, 'are')searches inside the string- PHP finds
'are'starting at index4 - So
$resultbecomes4 - The condition checks
4 !== false - That is true, so PHP prints
true
Character positions
H o w a r e y o u ?
0 1 2 3 4 5 6 7 8 9 10 11
The substring 'are' starts at position 4.
Another example
$a = 'apple pie';
$result = strpos($a, 'apple');
var_dump($result);
Output:
int(0)
This shows why if (strpos(...)) is dangerous. 0 means found at the beginning, but a plain if (0) would act like false.
Real World Use Cases
Checking whether a string contains text is used everywhere in real programs.
Common examples
- Form validation
- Check whether an email contains
@
- Check whether an email contains
- URL handling
- Detect whether a URL contains
/admin
- Detect whether a URL contains
- Search filters
- Show only products whose names contain a keyword
- Log analysis
- Find error lines that contain
warningorfailed
- Find error lines that contain
- Content moderation
- Detect blocked words in comments or messages
- API processing
- Check response text for expected markers or status phrases
Example: simple keyword filter
$message = 'Your order has been shipped';
if (str_contains($message, 'shipped')) {
echo 'Send shipping notification';
}
Example: URL rule
$url = '/admin/users';
if (str_contains($url, '/admin')) {
echo 'Admin route';
}
Real Codebase Usage
In real PHP codebases, developers usually combine string checks with other patterns such as validation, guard clauses, configuration rules, and filtering.
Guard clauses
A guard clause exits early when a required string pattern is missing.
$token = $_GET['token'] ?? '';
if (!str_contains($token, '-')) {
die('Invalid token format');
}
Input validation
$email = $_POST['email'] ?? '';
if (!str_contains($email, '@')) {
$errors[] = 'Email must contain @';
}
Filtering arrays of strings
$files = ['report.pdf', 'image.png', 'notes.txt'];
$pdfs = array_filter($files, fn($file) => str_contains($file, '.pdf'));
print_r($pdfs);
Configuration-driven checks
$blockedWords = ['spam', 'fake', 'scam'];
$comment = 'This looks like spam content';
foreach ($blockedWords as $word) {
if (str_contains($comment, $word)) {
echo 'Blocked comment';
break;
}
}
Error handling and logging
$logLine = 'Database connection failed';
if (str_contains($logLine, 'failed')) {
error_log('Critical issue detected');
}
In production code, developers also think about:
- case sensitivity
- whole-word matching versus partial matching
- multibyte text
- PHP version compatibility
Common Mistakes
1. Forgetting !== false with strpos()
Broken code:
$a = 'apple pie';
if (strpos($a, 'apple')) {
echo 'Found';
}
Why it fails:
strpos($a, 'apple')returns00is treated as false- The condition fails even though the substring exists
Correct version:
if (strpos($a, 'apple') !== false) {
echo 'Found';
}
2. Assuming the check is case-insensitive
Broken assumption:
$a = 'Hello World';
var_dump(str_contains($a, 'world')); // false
Why:
str_contains()andstrpos()are case-sensitive
One simple approach:
$a = 'Hello World';
if (str_contains(strtolower($a), 'world')) {
echo 'Found';
}
3. Expecting whole-word matching
$a = 'careful';
var_dump(str_contains($a, 'are')); // true
This matches because 'are' appears inside 'careful'.
If you need a whole word, substring search alone may not be enough. You may need regular expressions with word boundaries.
4. Using contains as if it were PHP syntax
Broken code:
if ($a contains 'are') {
echo 'true';
}
Why:
- PHP has no
containsoperator for strings
Use this instead:
if (str_contains($a, 'are')) {
echo 'true';
}
5. Not checking PHP version
str_contains() is available in PHP 8+.
If you are on an older PHP version, use:
if (strpos($a, 'are') !== false) {
echo 'true';
}
Comparisons
| Approach | PHP Version | Return Value | Best Use | Notes |
|---|---|---|---|---|
strpos($text, $search) | Older and newer PHP | Integer position or false | When you need the index or broad compatibility | Must use !== false |
str_contains($text, $search) | PHP 8+ | true or false | When you only need existence | Cleaner and easier to read |
stripos($text, $search) | Older and newer PHP | Integer position or false | Case-insensitive search | Also needs !== false |
preg_match() | Older and newer PHP | 1 or 0 | Complex patterns or whole-word matching | More powerful but more complex |
strpos() vs str_contains()
- Use
strpos()when:- you support older PHP versions
- you need the position of the match
- Use
str_contains()when:- you use PHP 8+
- you only care whether the substring exists
str_contains() vs preg_match()
str_contains()is simpler for basic substring checkspreg_match()is better for pattern matching, such as whole words or flexible formats
Cheat Sheet
Quick syntax
strpos($text, $search) !== false
str_contains($text, $search) // PHP 8+
Examples
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'Found';
}
if (str_contains($a, 'are')) {
echo 'Found';
}
Rules to remember
- PHP does not have a string
containsoperator strpos()returns:0,1,2, ... if foundfalseif not found
- Always use
!== falsewithstrpos() str_contains()returns a boolean directly- Both are case-sensitive by default
Useful alternatives
stripos($text, $search) !== false // case-insensitive
preg_match('/\bare\b/', $text) // whole word match
Edge cases
- Match at index
0is still a valid match 'Are'and'are'are different in case-sensitive checks- Substring matching is not the same as whole-word matching
FAQ
How do I check if a string contains a substring in PHP?
Use either strpos($text, $search) !== false or str_contains($text, $search) in PHP 8+.
Why is strpos() compared with !== false?
Because strpos() returns the starting position of the match. If the match starts at index 0, that is a valid result and should not be treated as false.
Is there a contains operator in PHP?
No. PHP does not provide a string contains operator like if ($a contains 'x').
What is the easiest way in PHP 8 to check if text exists in a string?
Use str_contains($text, $search). It is clearer and returns true or false directly.
How do I do a case-insensitive contains check in PHP?
You can use stripos($text, $search) !== false or convert both strings to the same case before checking.
How do I check for a whole word instead of part of a word?
Use a regular expression with word boundaries, such as preg_match('/\bare\b/', $text).
Which should I use: strpos() or str_contains()?
Use str_contains() if you are on PHP 8+ and only need a yes/no result. Use strpos() if you need the position or must support older PHP versions.
Mini Project
Description
Build a small PHP keyword checker that scans a message and tells you whether it contains important words. This mirrors real tasks such as content moderation, notification triggers, and simple text validation.
Goal
Create a PHP script that checks a sentence for one or more keywords and prints whether each keyword was found.
Requirements
- Create a string variable that stores a message.
- Create an array of keywords to search for.
- Loop through the keywords and check whether each one appears in the message.
- Print a clear result for each keyword.
- Use a solution that works in modern PHP.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.