Current Location: Home> Latest Articles> PHP Substring Detection: Detailed Guide to strstr and stripos Functions

PHP Substring Detection: Detailed Guide to strstr and stripos Functions

gitbox 2025-06-23

How to Detect If a Substring Exists in PHP

1. Introduction

In PHP development, it's common to check if a string contains another substring. This is useful for validating user input, implementing search features, and more. This article introduces two commonly used PHP functions to help detect the existence of substrings.

2. The strstr Function

PHP offers several ways to detect substrings, with strstr being one of the most frequently used. The basic syntax is as follows:

<span class="fun">mixed strstr(string $haystack, mixed $needle [, bool $before_needle = false])</span>

2.1 haystack

The main string to search in.

2.2 needle

The substring to find.

2.3 before_needle (optional)

A boolean value, defaulting to false. If true, strstr returns the part of the string before needle; otherwise, it returns needle and the rest of the string.

strstr searches for the first occurrence of needle in haystack and returns the substring from that position to the end. Returns false if needle is not found.

3. Example

$haystack = "Hello, World!";
$needle = "World";
if (strstr($haystack, $needle)) {
    echo "Substring found";
} else {
    echo "Substring not found";
}

This code outputs "Substring found" because needle exists in haystack.

4. The stripos Function

Another method to detect substrings is stripos, which is similar to strstr but case-insensitive. The syntax is:

<span class="fun">int stripos(string $haystack, string $needle [, int $offset = 0])</span>

4.1 haystack

The main string.

4.2 needle

The substring to search for.

4.3 offset (optional)

An integer specifying the starting position of the search, default is 0.

stripos returns the position of the first occurrence of needle in haystack, or false if not found.

5. Example

$haystack = "Hello, World!";
$needle = "WORLD";
if (stripos($haystack, $needle) !== false) {
    echo "Substring found";
} else {
    echo "Substring not found";
}

This code outputs "Substring found" because stripos ignores case and matches needle.

6. Conclusion

This article introduced two common PHP functions to check if a substring exists: strstr and stripos. strstr is case-sensitive and returns the substring from the match onward; stripos is case-insensitive and returns the position of the match. Developers can choose the appropriate function based on their needs to implement flexible string detection.

Mastering these methods helps improve text processing efficiency in PHP development, useful for input validation, search filtering, and many other scenarios.