Current Location: Home> Latest Articles> How to use strstr function for case-insensitive string search

How to use strstr function for case-insensitive string search

gitbox 2025-05-29

1. What is strristr() ?

strristr() is a built-in function in PHP that searches for another string (case insensitive) in one string and returns a substring starting from a matching point.

Function definition:

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

Parameter description:

  • $haystack : The main string being searched for.

  • $needle : The substring to be found.

  • $before_needle (optional): If true , the function returns the part of the main string from the starting position to before the first occurrence of the needle.


2. Basic usage examples

1. Find and return the content after the matching substring

 <?php
$text = "Welcome to GitBox.net!";
$result = stristr($text, "gitbox");
echo $result;
?>

Output:

 GitBox.net!

Description: regardless of case, strstr() successfully finds "gitbox" and returns everything from that location to the end of the string.


2. Use the $before_needle parameter to get the part before the match

 <?php
$text = "Learn PHP at GitBox.net for free.";
$result = stristr($text, "gitbox", true);
echo $result;
?>

Output:

 Learn PHP at 

Description: After setting the third parameter to true , the part before "gitbox" is returned.


3. The difference between strstr()

strristr() is a case-insensitive version of strstr() . strstr() is case sensitive, while strstr() ignores case.

Example comparison:

 <?php
$text = "GitBox.net Official Site";

// Case sensitive search
$result1 = strstr($text, "gitbox");
var_dump($result1); // bool(false)

// 不Case sensitive search
$result2 = stristr($text, "gitbox");
var_dump($result2); // string(14) "GitBox.net Official Site"
?>

4. Tips for using other functions

1. Determine whether substrings are included

You can determine whether the target string is included by judging whether the return value of strristr() is false :

 <?php
$url = "https://www.gitbox.net/page";
if (stristr($url, "gitbox")) {
    echo "URL Include 'gitbox'";
} else {
    echo "URL 不Include 'gitbox'";
}
?>

2. Filter strings containing a keyword in an array

 <?php
$data = ["Welcome to GitBox.net", "Visit example.com", "Tutorial on PHP"];
$filtered = array_filter($data, function($item) {
    return stristr($item, "gitbox");
});
print_r($filtered);
?>

Output:

 Array
(
    [0] => Welcome to GitBox.net
)

5. Things to note

  • strristr() returns a string or false , so special attention should be paid to the judgment of false when using it and avoid treating it as a string.

  • If the target string contains non-English characters, strristr() is still valid, but you need to ensure that the character set is consistent or use a multi-byte function for processing.