How to Use strstr() Function in PHP 8.4 and PHP 8.5?

The strstr() function behaves identically in PHP 8.4 and PHP 8.5. There are no version-specific changes or deprecations for this function in either release. The most recent behavioral changes date back to PHP 8.0.0.

Function

strstr() finds the first occurrence of a string within another string and returns the portion of the haystack from that point to the end. It is case-sensitive.

Signature:

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

Key Behavior:

Return Value: Returns the matched substring (including the needle), or false if the needle is not found.
$before_needle Parameter: If set to true, it returns the part of the haystack before the first occurrence of the needle.
Case Sensitivity: For case-insensitive searches, you should use stristr() instead.

Example

A common use case is extracting the domain from an email address:

<?php
$email  = name@example.com ;

// Get everything from the @ onwards
$domain = strstr($email, @ );
echo $domain; // Outputs: @example.com

// Get everything before the @
$user = strstr($email, @ , true);
echo $user; // Outputs: name
?>

This example is standard and works across all supported PHP 8.x versions.

Notes

→Empty Needle (PHP 8+): As of PHP 8.0.0, if the $needle is an empty string, strstr() returns the entire $haystack string (or an empty string if $before_needle is true), rather than false.
→Type Checking: When checking if a match was found, always use strict comparison (!== false). This is important because a valid match could return a string like "0", which would loosely evaluate to false.
 

17 Views