W3docs

strstr()

The strstr() function in PHP is used to find the first occurrence of a string inside another string. It returns the part of the haystack string starting from

Introduction

The strstr() function in PHP finds the first occurrence of a string inside another string. It returns the portion of the haystack starting from the needle to the end. This article covers its syntax, behavior, and usage.

Understanding the strstr() function

The syntax for using the strstr() function in PHP is as follows:

The PHP syntax of the strstr()

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

Here, $haystack is the string in which we want to find the $needle. The $needle parameter is the string that we want to search for inside the $haystack. The $before_needle parameter is an optional boolean. By default (false), the function returns the portion of $haystack from the first occurrence of $needle to the end. If set to true, it returns the portion of $haystack before the first occurrence of $needle.

Note that strstr() is case-sensitive. For case-insensitive matching, use stristr().

The strstr() function returns the part of the $haystack string starting from the first occurrence of the $needle string to the end of the $haystack string. If the $needle parameter is not found in the $haystack, the function returns false.

Example Usage

Here is an example usage of the strstr() function in PHP:

Example of PHP strstr()

<?php

$string = "Hello World";
$substring = "World";

$result = strstr($string, $substring);

echo "The first occurrence of '$substring' in '$string' is '$result'";

In the example above, we define a string $string and a substring $substring. We use the strstr() function to find the first occurrence of the $substring inside the $string. Since the $substring is present in the $string, the output will be "The first occurrence of 'World' in 'Hello World' is 'World'".

Using the optional parameter and handling false

<?php

$text = "Hello World";

// Returns the part before the needle
echo strstr($text, "World", true); // Outputs: Hello

// Returns false when the needle is not found
var_dump(strstr($text, "PHP")); // Outputs: false

Conclusion

The strstr() function efficiently locates substrings within larger strings. Understanding its case-sensitive behavior and optional parameters helps developers write more precise PHP code.

Practice

Practice

What is the function of the 'strstr' in PHP?