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
str_contains(string $haystack, string $needle): bool
Example
Let's check if the string contains a specified character:
<?php
$str = 'abcde';
$res = str_contains($str, 'a');
var_dump($res);
?>
Code execution result:
true
Example
Let's check if the string contains a specified substring:
<?php
$str = 'abcde';
$res = str_contains($str, 'ab');
var_dump($res);
?>
Code execution result:
true
Example
Now let's search for the substring
'ac'
in our string:
<?php
$str = 'abcde';
$res = str_contains($str, 'aс');
var_dump($res);
?>
Code execution result:
false
See Also
-
the
str_starts_with
function,
which checks the beginning of a string -
the
str_ends_with
function,
which checks the end of a string -
the
in_array
function,
which checks for the presence of an element in an array -
the
strpos
function,
which returns the position of a substring occurrence