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 ;
}
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
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 .
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
= ;
((, )) {
;
}
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(, ));
();
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(, ));
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 |
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, , ... if found
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 .
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
Converting HTML and CSS to PDF in PHP: Core Concepts, Limits, and Practical Approaches
Learn how HTML-to-PDF conversion works in PHP, why CSS support varies, and how to choose practical approaches for reliable PDF output.
How PHP foreach Actually Works with Arrays
Learn how PHP foreach works internally, including array copies, internal pointers, by-value vs by-reference behavior, and common pitfalls.
How to Check String Prefixes and Suffixes in PHP
Learn how to check whether a string starts or ends with specific text in PHP using simple functions and practical examples.