PHP 8 reference · String Functions
PHP str_contains() Function
Check whether a string contains a substring and return true or false. Case-sensitive; added in PHP 8.0.
PHP 8 Since 8.0
Syntax
str_contains(string $haystack, string $needle): bool
Parameters
| Parameter | Description |
|---|---|
haystack |
The string to search in. |
needle |
The string to look for. |
Return value
true or false.
Examples
<?php
var_dump(str_contains("ReadyCamel", "Camel"));
var_dump(str_contains("ReadyCamel", "camel"));
Output
bool(true) bool(false)
<?php
$agent = "Mozilla/5.0 (Android 14)";
echo str_contains(strtolower($agent), "android") ? "Android" : "other", "\n";
var_dump(str_contains("abc", "")); // an empty needle is always found
Output
Android bool(true)
Before PHP 8.0 the usual check was strpos($haystack, $needle) !== false. str_contains() says the same thing
clearly and avoids the position-0 trap.
Version history
| Version | Change |
|---|---|
| PHP 8.0 | Added |
In other languages
string.includes()· JavaScript
Related
str_starts_with()· Check whether a string begins with a given substring. Case-sensitive and returns true or false; added in PHP 8.0.str_ends_with()· Check whether a string ends with a given substring, such as a file extension. Case-sensitive; added in PHP 8.0.strpos()· Find the position of the first occurrence of a substring. Returns false if it's not found, so compare with === false.stripos()· Find the position of the first occurrence of a substring, ignoring case. Returns false when there's no match.- PHP Strings · tutorial