stristr() Function Use in PHP 8.4 and PHP 8.5

The stristr() function behaves identically in PHP 8.4 and PHP 8.5. There are no version-specific changes to this function in either release. Its most recent behavioral change occurred in PHP 8.2.0 regarding locale sensitivity.

Function Overview

stristr() finds the first occurrence of a string within another string, ignoring case, and returns the portion of the haystack from that point to the end.

Signature:

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

Examples

Here is how you can use it in your PHP 8.4 or 8.5 projects:

1. Basic Usage (Case-Insensitive)

<?php
$email = USER@EXAMPLE.com ;
// Search for lowercase e in a mostly uppercase string
echo stristr($email, e ); 
// Outputs: ER@EXAMPLE.com
?>

Because the search is case-insensitive, it matches the first "E" it finds, regardless of case.

2. Using the $before_needle Parameter

<?php
$email = USER@EXAMPLE.com ;
// Set third parameter to true to get the part BEFORE the match
echo stristr($email, e , true); 
// Outputs: US
?>

This is useful for extracting a username or prefix before a specific delimiter.

3. Checking if a String Exists

<?php
$string = Hello World! ;
if (stristr($string, earth ) === FALSE) {
   echo "earth" not found in string ;
}
// Outputs: "earth" not found in string
?>

Always use strict comparison (===) against false to check for a non-match, as an empty string or "0" could evaluate loosely.

3 Views