PHP Tutorial: stripos() Function – Complete Guide with Examples

When working with PHP strings, you may need to search for a word or phrase even when its uppercase and lowercase letters do not match. For example, a user might enter "php", while the stored text contains "PHP". A regular case-sensitive search would treat these as different values. The stripos() function solves this problem by finding the first occurrence of a substring without considering letter case.

PHP stripos() function example showing case-insensitive string search
PHP stripos() Function: Find the Position of a Substring Without Case Sensitivity

The stripos() function searches a string for the first occurrence of another string and returns its position. Unlike strpos(), it performs a case-insensitive search. If the specified text cannot be found, it returns false.

For example, searching for "php" inside "I am learning PHP" successfully finds the match, even though the letter case is different.

What Is the stripos() Function in PHP?

The stripos() function is a built-in PHP string function used to locate the first occurrence of a substring inside another string without matching uppercase and lowercase letters exactly.

This function is useful when searching text that may contain different letter combinations. For example, you can search for a keyword in a user message, check whether a product description contains a particular term, or find a word in stored text regardless of its capitalization.

One important detail is that stripos() returns a zero-based position. This means the first character of a string is at position 0, not 1.

Syntax of stripos() in PHP

The syntax of the stripos() function is:

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

Here is what each parameter means:

  • $haystack: The string in which PHP searches for the specified text.
  • $needle: The substring you want to find inside the main string.
  • $offset: An optional integer that specifies the position from which the search begins. Its default value is 0.

The function returns an integer position when a match is found or false when the specified substring does not exist.

Return Value of stripos()

The stripos() function returns one of two possible results:

  • Integer: The zero-based position of the first matching substring.
  • false: Returned when the specified substring cannot be found.

For example, if the matching text starts at the beginning of a string, the function returns 0. This is a valid search result, not a failure.

Because 0 and false can both behave like false in a conditional statement, use the strict comparison operator !== false when checking whether a match exists.

Example 1: Basic Usage of stripos() in PHP

Let's start with a simple example that searches for a word inside a string. The search will work even when the letter case is different.

<?php
$text = "I am learning PHP programming";

$position = stripos($text, "php");

var_dump($position);
?>

Output: int(14)

Explanation: The string contains "PHP" in uppercase, but the search uses "php" in lowercase. Since stripos() ignores letter case, it finds the matching word at position 14.

Example 2: Check Whether a String Contains Text

You can use stripos() to check whether a string contains a particular word or phrase without worrying about capitalization.

<?php
$message = "Welcome to PHP Development";

if (stripos($message, "development") !== false) {
    echo "The text was found.";
} else {
    echo "The text was not found.";
}
?>

Output: The text was found.

Explanation: The search term "development" is written in lowercase, while the message contains "Development" with an uppercase first letter. The function still finds the match because it performs a case-insensitive search.

Example 3: Search for Text with Different Letter Cases

One of the main advantages of stripos() is that it treats uppercase and lowercase versions of the same ASCII letters as equivalent during a search.

<?php
$text = "PHP is a popular programming language";

var_dump(stripos($text, "PHP"));
var_dump(stripos($text, "php"));
var_dump(stripos($text, "Php"));
?>

Output:
int(0)
int(0)
int(0)

Explanation: All three searches find the same word at position 0. The function does not require the search term to have the same capitalization as the original text.

Example 4: Why You Should Use !== false with stripos()

A common mistake is to use the return value of stripos() directly in an if condition. This can produce an incorrect result when the matching text appears at the beginning of a string.

Incorrect example:

<?php
$text = "PHP is easy to learn";

if (stripos($text, "php")) {
    echo "Text found.";
} else {
    echo "Text not found.";
}
?>

Output: Text not found.

Why does this happen? The word "PHP" starts at position 0, so the function returns the integer 0. PHP treats 0 as false in a conditional statement, even though the search was successful.

Correct example:

<?php
$text = "PHP is easy to learn";

if (stripos($text, "php") !== false) {
    echo "Text found.";
} else {
    echo "Text not found.";
}
?>

Output: Text found.

Explanation: The strict comparison !== false distinguishes the integer 0 from the boolean value false. This ensures that a match at the beginning of the string is handled correctly.

Example 5: Search for a Character Without Case Sensitivity

The stripos() function can also search for a single character. This is useful when you need to locate a particular letter without knowing whether it appears in uppercase or lowercase.

<?php
$text = "Welcome to PHP";

$position = stripos($text, "p");

echo $position;
?>

Output: 11

Explanation: The letter "P" appears in uppercase in the original string, but the search uses lowercase "p". The function finds the first matching character at position 11.

Example 6: Use the Offset Parameter in stripos()

The optional $offset parameter tells PHP where to begin searching inside the original string. It is useful when the same word appears more than once and you want to find a later occurrence.

<?php
$text = "PHP is useful. php is popular.";

$position = stripos($text, "PHP", 1);

var_dump($position);
?>

Output: int(15)

Explanation: The first occurrence of "PHP" starts at position 0. Since the search begins at offset 1, PHP skips that occurrence and finds the next matching word at position 15.

The offset changes where the search starts, but the returned position is still calculated from the beginning of the original string.

Example 7: Find the Second Occurrence of a Word

You can combine stripos() with its offset parameter to find repeated occurrences of a word. First, locate the initial match and then begin another search after that match.

<?php
$text = "PHP is useful. php is popular.";

$firstPosition = stripos($text, "php");

if ($firstPosition !== false) {
    $secondPosition = stripos($text, "php", $firstPosition + strlen("php"));

    var_dump($secondPosition);
}
?>

Output: int(15)

Explanation: The first occurrence begins at position 0. The strlen() function calculates the length of the search term, allowing the next search to begin immediately after the first occurrence. The second matching word is found at position 15.

You can also read our guide to the strlen() function to understand how PHP calculates string length.

Example 8: Use a Negative Offset in stripos()

PHP also supports negative offset values. A negative offset starts the search from a position counted backward from the end of the string. This can be useful when you want to limit a search to a particular portion of a string.

<?php
$text = "PHP makes web development easier";

$position = stripos($text, "development", -20);

var_dump($position);
?>

Output: int(14)

Explanation: The negative offset -20 tells PHP to begin searching 20 positions from the end of the string. The word "development" is found at position 14, measured from the beginning of the original string.

Negative offsets have been supported by stripos() since PHP 7.1.0.

Example 9: Search for a Keyword in User Input

Suppose a user submits a message containing a keyword. You can use stripos() to check whether that keyword appears in the message, regardless of its capitalization.

<?php
$userMessage = "I want to learn PHP development";

if (stripos($userMessage, "LEARN") !== false) {
    echo "The message contains the keyword.";
} else {
    echo "The keyword was not found.";
}
?>

Output: The message contains the keyword.

Explanation: The message contains "learn" in lowercase, while the search term is written as "LEARN". The function finds the matching text because it ignores letter case.

Remember that finding a keyword is not the same as validating or sanitizing user input. Use appropriate validation and security checks when handling data submitted by users.

Example 10: Handle a Substring That Is Not Found

When the specified substring does not exist, stripos() returns false. You can check this result and display a suitable message.

<?php
$text = "Learning Laravel is useful";

$position = stripos($text, "Python");

if ($position !== false) {
    echo "Found at position: " . $position;
} else {
    echo "The text was not found.";
}
?>

Output: The text was not found.

Explanation: The string does not contain "Python", so the function returns false. The condition correctly identifies that the search was unsuccessful.

Does stripos() Work with Non-ASCII Characters?

An important detail about stripos() is that its case-insensitive matching is not a complete Unicode-aware text search.

Since PHP 8.2.0, case folding in stripos() is limited to ASCII letters and no longer depends on the locale set with setlocale(). Non-ASCII bytes are compared by their byte values.

For example, if your application needs case-insensitive searching in languages that use accented characters or other non-ASCII alphabets, consider using the mb_stripos() function instead.

The mb_stripos() function is part of PHP's Multibyte String extension and is designed for case-insensitive searches involving multibyte text.

Common Mistakes When Using stripos()

When working with stripos() in PHP, keep these common mistakes in mind:

  • Using a loose conditional check: Do not use the function's return value directly in an if condition. Use !== false to handle matches at position 0 correctly.
  • Assuming it is fully Unicode-aware: The function performs ASCII case-insensitive matching, not general Unicode case folding. Use mb_stripos() when appropriate.
  • Ignoring zero-based positions: The first character of a string is at position 0, not position 1.
  • Misunderstanding the offset: The offset specifies where the search begins, but the returned position is still relative to the original string.
  • Passing an invalid offset: An offset greater than the length of the string causes a ValueError.
  • Passing an integer as the search term: The needle must be a string. Explicitly convert numeric search values to strings when necessary.

Difference Between strpos(), stripos(), str_contains(), and mb_stripos()

PHP provides several string functions for searching text. Although they may seem similar, each one serves a different purpose.

Function Purpose Case-Sensitive? Return Value
strpos() Finds the first position of a substring. Yes Integer or false
stripos() Finds the first position without matching ASCII letter case. No Integer or false
str_contains() Checks whether a string contains another string. Yes true or false
mb_stripos() Finds a substring using multibyte-aware case-insensitive searching. No Integer or false

Choose the function based on your requirements. Use strpos() for case-sensitive position searches, stripos() for ASCII case-insensitive position searches, str_contains() when you only need a case-sensitive contains check, and mb_stripos() for multibyte-aware searches.

You can also read our guides to PHP str_contains(), PHP strlen(), and PHP count_chars() to learn more about PHP string handling.

Best Practices for Using stripos()

  • Use !== false when checking whether a substring exists.
  • Remember that PHP string positions start at 0.
  • Use stripos() when an ASCII case-insensitive search is required.
  • Use the offset parameter when searching for later occurrences of a substring.
  • Convert numeric search values to strings explicitly before passing them as the needle.
  • Use mb_stripos() when your application needs multibyte-aware case-insensitive searching.
  • Validate user-provided search values when your application requires a non-empty string.
  • Choose a different function when you only need to check whether a string contains text without retrieving its position.

Frequently Asked Questions (FAQs)

1. What does stripos() do in PHP?

The stripos() function searches a string for the first occurrence of another string without considering ASCII letter case. It returns the position of the match or false if the text is not found.

2. Is stripos() case-sensitive in PHP?

No. The stripos() function performs a case-insensitive search. For example, searching for "php" can match "PHP" in the original string.

3. What does stripos() return if the text is not found?

If the specified substring does not exist, stripos() returns the boolean value false.

4. Why should I use !== false with stripos()?

The function can return 0 when the match appears at the beginning of a string. Since 0 can evaluate to false in a conditional statement, !== false helps distinguish a successful search from an unsuccessful one.

5. What is the offset parameter in stripos()?

The optional offset parameter specifies where PHP should begin searching. It is useful when you want to find another occurrence of a substring after its first match.

6. What is the difference between strpos() and stripos()?

strpos() performs a case-sensitive search, while stripos() performs a case-insensitive search. Both return the position of the first match or false if the substring is not found.

7. Does stripos() support negative offsets?

Yes. Since PHP 7.1.0, stripos() supports negative offsets. A negative value specifies a starting position counted backward from the end of the string.

8. Is stripos() Unicode-aware?

No. Since PHP 8.2.0, its case folding is limited to ASCII letters. For multibyte-aware case-insensitive searching, use mb_stripos() instead.

9. What happens if the offset is greater than the string length?

If the offset is greater than the length of the haystack, PHP throws a ValueError.

10. Can stripos() search for a single character?

Yes. The stripos() function can search for a single character as well as a complete word or phrase. It returns the position of the first matching occurrence.

Conclusion

The PHP stripos() function is useful when you need to find text inside a string without worrying about uppercase and lowercase differences. It returns the position of the first matching substring, making it suitable for keyword searches, user messages, and other text-processing tasks.

The most important thing to remember is that stripos() returns an integer position or false. Always use a strict comparison such as stripos($text, $search) !== false when checking whether a match exists. Also, keep its ASCII case-insensitive behavior in mind when working with multilingual text. Understanding its parameters, return value, and limitations will help you use this function more reliably in PHP applications.

Post a Comment

Previous Post Next Post