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.
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>
The main string to search in.
The substring to find.
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.
$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.
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>
The main string.
The substring to search for.
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.
$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.
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.