Question

How to Check if a String Contains a Word in PHP

phpstringsubstringcontainsstring-matching

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 versions
  • str_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:

  • 0 means it starts at the first character
  • 4 means it starts at the fifth character
  • false means it was not found at all

With str_contains(), PHP gives a simpler answer:

  • true if found
  • false if not found

So:

  • strpos() answers: Where is it?
  • str_contains() answers: Is it there?
Take Quiz

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
  • !== false is required so that position 0 is not confused with false

Using str_contains() in PHP 8+

$a = 'How are you?';

if (str_contains($a, 'are')) {
    echo 'true';
}

Explanation

  • str_contains() directly returns true or false
  • 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

  1. $a is assigned the string 'How are you?'
  2. strpos($a, 'are') searches inside the string
  3. PHP finds 'are' starting at index 4
  4. So $result becomes 4
  5. The condition checks 4 !== false
  6. 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 @
  • URL handling
    • Detect whether a URL contains /admin
  • Search filters
    • Show only products whose names contain a keyword
  • Log analysis
    • Find error lines that contain warning or failed
  • 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';
}
Take Quiz

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') returns 0
  • 0 is 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() and strpos() 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 contains operator 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

ApproachPHP VersionReturn ValueBest UseNotes
strpos($text, $search)Older and newer PHPInteger position or falseWhen you need the index or broad compatibilityMust use !== false
str_contains($text, $search)PHP 8+true or falseWhen you only need existenceCleaner and easier to read
stripos($text, $search)Older and newer PHPInteger position or falseCase-insensitive searchAlso needs !== false
preg_match()Older and newer PHP1 or 0Complex patterns or whole-word matchingMore 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 checks
  • preg_match() is better for pattern matching, such as whole words or flexible formats
Take Quiz

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 contains operator
  • strpos() returns:
    • 0, 1, 2, ... if found
    • false if not found
  • Always use !== false with strpos()
  • 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 0 is 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.

Take Quiz

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.
Take Quiz

Keep learning

Related questions

View more