The str_contains Function
The str_contains function checks for the presence
of a character in a string. It returns true
if the character is found in the string, and false otherwise.
The first parameter of the function is the string to search in.
The second parameter specifies the desired character or substring.
Syntax
phpstr_contains(string $haystack, string $needle): bool
Example
Let's check if the string contains a specified character:
php<?php
$str = 'abcde';
$res = str_contains($str, 'a');
var_dump($res);
?>
Code execution result:
phptrue
Example
Let's check if the string contains a specified substring:
php<?php
$str = 'abcde';
$res = str_contains($str, 'ab');
var_dump($res);
?>
Code execution result:
phptrue
Example
Now let's search for the substring
'ac' in our string:
php<?php
$str = 'abcde';
$res = str_contains($str, 'ac');
var_dump($res);
?>
Code execution result:
phpfalse
See Also
-
the
str_starts_withfunction,
which checks the beginning of a string -
the
str_ends_withfunction,
which checks the end of a string -
the
in_arrayfunction,
which checks for the presence of an element in an array -
the
strposfunction,
which returns the position of a substring occurrence