Current Location: Home> Latest Articles> What is the difference between stripos and strpos?

What is the difference between stripos and strpos?

M66 2025-05-17

In PHP programming, we often encounter the need for string search, such as determining whether a substring exists in another string. PHP provides multiple built-in functions for this, the two most commonly used are strpos() and strpos() . Although their usage looks very similar, they behave with a key difference: whether it is case sensitive.

1. strpos() : case-sensitive string search

strpos() is used to find where a string first appears in another string. This function is case sensitive .

grammar:

 int|false strpos(string $haystack, string $needle, int $offset = 0)
  • $haystack is the target string to search for.

  • $needle is the substring to be looked for.

  • $offset is an optional start position.

Example:

 $pos = strpos("Welcome to m66.net", "M");
if ($pos !== false) {
    echo "Found at position $pos";
} else {
    echo "Not found";
}

The output will be:

 Not found

The reason is that "M" is uppercase, and "m" in the original string is lowercase, strpos() will be strictly case sensitive, so it returns false .

2. stripos() : case-insensitive string search

Unlike strpos() , strpos() is a case-insensitive version. It is logically exactly consistent, just ignores the upper and lower case of characters.

grammar:

 int|false stripos(string $haystack, string $needle, int $offset = 0)

Example:

 $pos = stripos("Welcome to m66.net", "M");
if ($pos !== false) {
    echo "Found at position $pos";
} else {
    echo "Not found";
}

This code will output:

 Found at position 0

Because stripos() treats "M" and "m" as the same characters.

3. When should they be used?

Which function to choose depends on your specific needs:

  • If you need an exact match , such as checking whether a variable contains a specific case spelling (such as password verification), then using strpos() is more appropriate.

  • If you just want to determine whether a keyword exists and don't care about upper and lower case (such as in the search function), then stripos() is more convenient.

Practical Example: Filtering sensitive words (case insensitive)

 $comment = "This is a stupid comment.";
$badword = "Stupid";

if (stripos($comment, $badword) !== false) {
    echo "Warning: Inappropriate language detected.";
}

This can effectively detect sensitive words in various case combinations.

Summarize

function case sensitive Return value type use
strpos() yes int or false Accurate search
stripos() no int or false Ignore case searches

Understanding the difference between them and using them in the right scenario will make your code more precise and efficient. I hope this article can help you better understand the difference between these two functions!