Current Location: Home> Latest Articles> How strpos functions handle case-sensitive matching

How strpos functions handle case-sensitive matching

gitbox 2025-05-28

strpos() is case sensitive

The answer is:. This means that strpos() strictly matches the case difference of characters when comparing strings.

Let's look at a simple example:

<code> $haystack = "Hello World!"; $needle = "world";

$position = strpos($haystack, $needle);

if ($position === false) {
echo "No string found.";
} else {
echo "String position is: " . $position;
}
</code>

The output result is "No string found". Why? Because "world" in the needle is lowercase, and "World" in the haystack is uppercase. In case-sensitive comparisons, the two strings are not considered identical.


How to do case-insensitive matching?

If you want to do case-insensitive searches, PHP provides another function: stripos() . It works the same as strpos() , but is case-insensitive.

Example:

<code> $haystack = "Hello World!"; $needle = "world";

$position = stripos($haystack, $needle);

if ($position === false) {
echo "No string found.";
} else {
echo "String position is: " . $position;
}
</code>

This time the output will be:

 The string position is: 6

This means "world" (regardless of upper and lower case) starts from the 6th character in the string (counting from 0).


A practical scenario: URL check

Suppose you want to check whether a URL contains the domain name gitbox.net . You can use stripos() to achieve case-insensitive matching (because some users may use full or mixed case).

<code> $url = "https://www.GITBOX.net/page/123";

if (stripos($url, "gitbox.net") !== false) {
echo "URL contains gitbox.net";
} else {
echo "URL does not contain gitbox.net";
}
</code>

Even if GITBOX.net is in full capitalization, the program will still correctly recognize it.