PHP Reference ยท String Functions
PHP str_contains() function
Reference for PHP str_contains(): check whether a string contains a substring, case sensitivity, the empty needle rule, and how it replaces strpos() checks.
str_contains() returns true if the haystack contains the needle anywhere, and false otherwise. It was added in PHP 8.0 to replace the awkward idiom strpos($haystack, $needle) !== false, which is easy to get wrong because strpos() returns 0 for a match at the very start.
The search is case-sensitive and works on bytes, so it is safe for UTF-8 text as long as both strings use the same encoding. An empty needle always matches.
<?php var_dump(str_contains("Hello, world", "world")); // bool(true) var_dump(str_contains("Hello, world", "World")); // bool(false)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
str_contains(string $haystack, string $needle): bool
| Name | Description |
|---|---|
$haystack |
The string to search in. |
$needle |
The substring to look for. If it is empty, the result is true. |
Return value: true if $needle occurs in $haystack, otherwise false.
Errors: a TypeError is thrown for arguments that cannot be converted to string (such as arrays). With declare(strict_types=1), passing an int or float instead of a string also throws.
Usage notes
- Case-sensitive. For a case-insensitive test, lower-case both strings first, or use
stripos()and compare the result withfalse. - Empty needle is always found. Since PHP 8.0
str_contains($s, "")istrue, even for an empty haystack. Check for emptiness yourself if that matters. - No position information. If you need to know where the match is, use
strpos()and compare withfalseusing!==. - Byte-wise comparison. It does not normalize Unicode: a precomposed "รฉ" and "e" followed by a combining accent do not match each other.
- PHP version. Added in PHP 8.0. For older versions, use
strpos($h, $n) !== falseor a polyfill. Always use!== false, never a loose truthiness check. - Not a regular expression. Characters like
.and*are plain text here. For patterns usepreg_match(). - Performance. Linear in the length of the haystack and very fast; there is no reason to prefer
preg_match()for a plain substring test. - Related checks.
str_starts_with()andstr_ends_with()test the beginning and end only. - Array haystacks are not supported. To search an array use
in_array(); to test many needles, loop or build a regex withpreg_quote().