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"). Usestrpos() !== falseon 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 usestripos() !== false.