PHP str_contains() Function

Check whether a string contains a substring (PHP 8+)

Try str_contains() - edit and run
Output
bool(true)
bool(false)
bool(true)

What does str_contains() do?

str_contains(), added in PHP 8.0, answers one question: does $haystack contain $needle? It returns a real boolean, so it avoids the position-0 trap of strpos(). The comparison is case-sensitive.

Syntax

str_contains(string $haystack, string $needle): bool

Available since PHP 8.0.

Parameters

  • $haystack - The string to search in.
  • $needle - The substring to look for. An empty string is always "contained", so the function returns true.

Return value

true if $needle occurs in $haystack, otherwise false.

str_contains() examples

Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.

1. Basic usage

<?php
$text = "The quick brown fox";
var_dump(str_contains($text, "quick"));
var_dump(str_contains($text, "Quick"));
var_dump(str_contains($text, ""));

Output:

bool(true)
bool(false)
bool(true)

2. Case-insensitive check, starts with and ends with

<?php
$email = "[email protected]";
var_dump(str_contains(strtolower($email), "example"));
var_dump(str_starts_with($email, "Alice"));
var_dump(str_ends_with($email, ".com"));

Output:

bool(true)
bool(true)
bool(true)

3. PHP 7 equivalent and checking several keywords

<?php
$haystack = "error: file not found";

// Equivalent that also works on PHP 7
var_dump(strpos($haystack, "error") !== false);

$keywords = ["warning", "not found"];
$hits = array_filter($keywords, fn($k) => str_contains($haystack, $k));
print_r(array_values($hits));

Output:

bool(true)
Array
(
    [0] => not found
)

Common mistakes and gotchas

  • PHP version: str_contains() does not exist before PHP 8.0 ("Call to undefined function"). Use strpos() !== false on PHP 7.
  • Empty needle: str_contains($s, "") is always true, so validate user-supplied needles first.
  • Case: there is no str_icontains(); lower-case both strings or use stripos() !== false.

PHP str_contains() FAQ

Is str_contains() case-sensitive?

Yes. Compare lower-cased strings (str_contains(strtolower($a), strtolower($b))) or use stripos($a, $b) !== false for a case-insensitive check.

What is the difference between str_contains() and strpos()?

str_contains() returns a boolean. strpos() returns the match position or false, so a match at position 0 needs a strict comparison.

Which PHP version added str_contains()?

PHP 8.0, together with str_starts_with() and str_ends_with().