PHP Advent

#[Language]

PHP String Contains: str_contains and Substring Checks

By Rodney Renner ·

An illuminated archivist workbench features an ornate brass magnifying glass resting on an antique parchment scroll beside an open book of tree hierarchy diagrams and a dark fountain pen.

In PHP 8.0 and later, use str_contains($haystack, $needle) to check whether a string contains a specific substring. The function returns true if the needle exists within the haystack and false otherwise. It performs a case-sensitive search and treats an empty needle as present in any string.

Before PHP 8.0, developers used strpos() for substring checks. It returns the match's integer byte position, or boolean false on failure. A loose comparison can therefore miss a match at index 0, because PHP treats that value as falsy. The newer boolean functions avoid this bug. The function you need still depends on whether case matters, which encoding you use, and which PHP versions your code supports.

The Modern Solution: str_contains() in PHP 8+

PHP includes str_contains() in its standard library. The PHP str_contains manual gives its signature as str_contains(string $haystack, string $needle): bool.

This checks an input string for a domain name:

$email = "support@phpadvent.org";

if (str_contains($email, "phpadvent.org")) {
    // String contains the target substring
}

You can use the boolean result directly in a condition:

$message = "Database connection timed out after 30 seconds";

if (str_contains($message, "timed out")) {
    $shouldRetry = true;
}

How str_contains() Handles Empty Needles

The accepted str_contains RFC defines an empty string as occurring at every position in any string, including another empty string:

str_contains("hello", ""); // returns true
str_contains("", "");      // returns true

With this convention, an optional query term that is empty will not cause a collection filter to reject matches. If your application treats an empty query as invalid, check the needle's length before searching.

Strict Typing and Null Values

Under declare(strict_types=1);, passing a non-string value to either $haystack or $needle triggers a TypeError. In coercive typing mode, PHP may convert scalar values to strings. Passing null to a non-nullable parameter is deprecated since PHP 8.1. Check that your variables contain strings before calling str_contains().

Boundary Checks: str_starts_with() and str_ends_with()

If you need a match at the beginning or end of a string, str_contains() is too broad: it also accepts matches in the middle.

PHP 8.0 introduced two functions for these checks, documented in the PHP str_starts_with reference:

$path = "/var/log/php-fpm.log";

// Check the start
$isVar = str_starts_with($path, "/var/"); // true

// Check the end
$isLog = str_ends_with($path, ".log");    // true

Their names tell someone reviewing the code which boundary you are checking, without extracting slices or writing a regular expression.

A precision brass marking gauge with an adjustable sliding stop aligns against a dark timber bar beside an open notebook showing geometric boundary diagrams.

Case-Insensitive Substring Checks

Searching for "php" inside "PHP Advent" with str_contains() returns false. To ignore case, use stripos() or convert both strings to lowercase before searching.

Option 1: stripos()

stripos() returns the integer position of the first case-insensitive match, or false if it finds none. The details are in the PHP stripos manual.

Compare the result with !== false so a match at the start of the string counts:

$logMessage = "CRITICAL: memory limit exceeded";

if (stripos($logMessage, "critical") !== false) {
    // Found, regardless of case
}

Option 2: Normalizing with strtolower()

If you prefer working with booleans directly, convert both the haystack and the needle to lowercase before passing them to str_contains():

$haystack = "Welcome to PHP Advent";
$needle = "php";

if (str_contains(strtolower($haystack), strtolower($needle))) {
    // Match found
}

For small strings, this is a readable way to avoid index comparison mistakes. With large texts, the copies matter: strtolower() allocates memory for a lowercase copy of each string. In loops where performance matters, stripos() uses less memory because it scans the original string without copying it.

Multibyte Strings and UTF-8 Encodings

Standard string functions in PHP operate on individual bytes. For ASCII text, byte offsets match character positions. With UTF-8 text containing accented characters, Cyrillic, Greek, or Asian scripts, byte-oriented functions can give unexpected results when folding case.

For case-insensitive checks on multibyte strings, use mb_stripos() from the multibyte string extension, as described in the PHP mb_stripos documentation:

$title = "München Hauptbahnhof";
$search = "münchen";

// Safe multibyte case-insensitive search
if (mb_stripos($title, $search, 0, "UTF-8") !== false) {
    // Found match in UTF-8 string
}

For case-sensitive UTF-8 checks, str_contains() works because identical character sequences have the same byte representation. You only need the mb_* functions when folding case or counting characters. Paul Reinheimer's archive article discusses encoding problems in more detail: character sets.

Legacy PHP Versions: The strpos() Zero Pitfall

On PHP 7.4 or earlier, str_contains() is not built in. Use strpos() and check its return value carefully.

The PHP strpos manual documents the integer-or-false return value. This example shows how a direct boolean check misses a match:

$text = "PHP Advent articles";
$needle = "PHP";

// BUG: $needle is at position 0, which evaluates to false
if (strpos($text, $needle)) {
    // This code will NOT run!
}

Use a strict comparison against false to distinguish a match at position 0 from a missing substring:

// CORRECT: Check against boolean false explicitly
if (strpos($text, $needle) !== false) {
    // This code runs as expected
}

For static analysis of older code, see PHPStan.

Writing a Backward-Compatible Polyfill

For code that must run on both PHP 7 and PHP 8, define a polyfill during bootstrap:

if (!function_exists("str_contains")) {
    function str_contains(string $haystack, string $needle): bool
    {
        return $needle === "" || strpos($haystack, $needle) !== false;
    }
}

This definition matches the behavior of PHP 8.0, including the empty needle rule.

Checking for Multiple Substrings

You may need to check whether a string contains any keyword from a list, or whether it contains all of them. This loop checks for any match and stops as soon as it finds one:

$input = "Error 504: gateway timeout occurred";
$alertWords = ["failed", "timeout", "critical"];

$hasAlert = false;
foreach ($alertWords as $word) {
    if (str_contains($input, $word)) {
        $hasAlert = true;
        break;
    }
}

For a literal substring, str_contains() avoids the pattern syntax of a regular expression.

Frequently Asked Questions

How do I check if a string does NOT contain a substring?

Place the logical NOT operator ! before the function call:

$message = "The request completed successfully";

if (!str_contains($message, "timed out")) {
    // No timeout phrase was found
}

Can I pass an array of needles to str_contains()?

No. str_contains() accepts only single strings for both arguments. If you pass an array, PHP throws a TypeError. To search for multiple needles, loop over the array with str_contains() or use array_any() where available.