Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
string
communitycreator

What is the strstr() function in PHP?

Dario Vincenzo Tarantini

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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).

RELATED TAGS

php
string
communitycreator

CONTRIBUTOR

Dario Vincenzo Tarantini

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring