How to Search for a String with the PHP strstr() Function

Contents
In this article, you will learn how to search for a string with the PHP strstr() function.
PHP strstr() Function
The strstr() function in PHP is used to search for the first occurrence of a string within another string. The function takes two parameters: $string
(the string to search in) and $search
(the string to search for).
Here’s an example of how to use the strstr() function:
<?php
$string = "How to search for a string with the php strstr() function";
$search = "search";
$result = strstr($string, $search);
echo $result;
?>
This will output:
search for a string with the php strstr() function
The strstr() function returns the portion of $string
starting from the first occurrence of $search
to the end of $string
.
It also has an optional third parameter which is a boolean value, if passed true it returns the part of $string
before $search
and if passed false it returns the part of $string
after $search
.
<?php
$string = "How to search for a string with the php strstr() function";
$search = "search";
$result = strstr($string, $search, true);
echo $result;
?>
This will output:
How to
If $search
is not found in $string
, the function will return false.
You can use the ===
operator to check if $search
was found in $string
:
<?php
if ($result === false) {
echo "$search was not found in $string.";
} else {
echo "$search was found in $string.";
}
?>
If $search
is an empty string, strstr() will return an empty string. If $search
is at the beginning of $string
, strstr() will return $string
.
You can also use strstr() with arrays, in this case it will search for the first matching value in the array.
Note that the strstr() function is case-sensitive, so if you want to perform a case-insensitive search, you can use the stristr() function instead.