What is the strstr() function in PHP?

Share

The strstr function in PHP is used to search for the first occurrence of a string in another string.

Note: This function is case-sensitive.

The illustration below shows how the strstr() function is used to search for a string:

Syntax

The prototype of the strstr() function is shown below:

strstr(string $haystack, string $needle, bool $before_needle = false):string|false

Parameters

The strstr() function requires two mandatory strings as parameters:

  • haystack: The string in which the search is carried out.

  • needle: The string you want to search for.

In addition to the parameters above, the strstr() function also accepts an optional parameter, before_needle, which truncates the input string when it finds needle.

Return value

The strstr() function returns the part of the input string searched for, or false if it fails to find the searched string.

Example

The code below shows the different results produced by the strstr() function when it searches for a string:

<?php
$w = '123456';
echo strstr($w, "4") . "\n";
echo strstr($w, "4", true);

In the first echo, we searched for the number 4. When we found it, the function returned the part of the haystack after that number.
In the second case, we set before_needle as true so the function returned the part of the haystack before the value we were searching for (and without the value).