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().
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
