Master PHP’s stristr() for Case‑Insensitive String Searches

Learn how PHP’s stristr() function performs a case‑insensitive search within a string, understand its syntax, parameters, return values, and see three practical code examples that illustrate basic usage, checking for absence, and using character codes, along with key differences from strstr().

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Master PHP’s stristr() for Case‑Insensitive String Searches

PHP’s stristr() function searches for the first occurrence of a substring within a string without regard to case.

Function Syntax

string stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

The function returns the portion of $haystack starting from the first match of $needle to the end of the string.

Parameters

haystack : The string to be searched.

needle : The substring to look for; if it is not a string it is cast to an integer representing a character code.

before_needle (optional): When set to true, the function returns the part of $haystack that appears before the first occurrence of $needle, excluding the needle itself.

Both $haystack and $needle are compared case‑insensitively.

Return Value

The function returns the matched portion of the string, or FALSE if the needle is not found.

Examples

Example 1 – Basic usage

<?php
$email = '[email protected]';
echo stristr($email, 'e');          // Outputs: [email protected]
echo stristr($email, 'e', true);    // From PHP 5.3.0, outputs: US
?>

Example 2 – Checking for absence

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

Example 3 – Using a character code

<?php
$string = 'APPLE';
echo stristr($string, 97); // 97 is the ASCII code for lowercase 'a', outputs: APPLE
?>

Note: Unlike strstr(), stristr() performs a case‑insensitive search.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPString Functionscase-insensitivephp-tutorialphp-stristr
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.