str_contains
Checks whether a string contains a given substring.
Available since: PHP 8.0
Syntax
str_contains(string $haystack, string $needle): boolParameters
| Parameter | Type | Description |
|---|---|---|
| $haystack | string | The string to search in. |
| $needle | string | The substring to look for. |
Return value
bool`true` if the substring is found, `false` otherwise.
Examples
A match and no match:
<?php
var_dump(str_contains('Hello, world', 'world'));
var_dump(str_contains('Hello, world', 'PHP'));Output:
bool(true)
bool(false)The search is case-sensitive:
<?php
var_dump(str_contains('Hello', 'hello'));Output:
bool(false)Notes
To search case-insensitively, convert both strings to the same case with mb_strtolower(). An empty substring is considered present in any string.
See also
- str_starts_with — Checks whether a string starts with a given substring.
- mb_strpos — Finds the position of the first occurrence of a substring.
Related recipes
In the tutorial
- Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.