0
0
PhpHow-ToBeginner · 3 min read

How to Find Substring in PHP: Simple Guide with Examples

In PHP, you can find a substring within a string using the strpos() function, which returns the position of the first occurrence of the substring or false if not found. Use strpos($string, $substring) to check if the substring exists and where it starts.
📐

Syntax

The strpos() function is used to find the position of the first occurrence of a substring in a string.

  • string $haystack: The full string to search in.
  • string $needle: The substring to find.
  • Returns the position (0-based index) of the first match or false if not found.
php
int strpos ( string $haystack , string $needle [, int $offset = 0 ] )
💻

Example

This example shows how to find the substring "world" inside a string and print its position. It also checks if the substring is found or not.

php
<?php
$text = "Hello world!";
$substring = "world";
$pos = strpos($text, $substring);

if ($pos !== false) {
    echo "Substring found at position: $pos";
} else {
    echo "Substring not found.";
}
?>
Output
Substring found at position: 6
⚠️

Common Pitfalls

A common mistake is to check the result of strpos() with == false instead of === false. Since strpos() can return 0 (which means the substring is at the start), using == false treats 0 as false and causes wrong results.

Always use !== false or === false to check the result properly.

php
<?php
// Wrong way
$pos = strpos("apple", "a");
if ($pos == false) {
    echo "Not found";
} else {
    echo "Found at $pos";
}

// Right way
$pos = strpos("apple", "a");
if ($pos === false) {
    echo "Not found";
} else {
    echo "Found at $pos";
}
?>
Output
Found at 0Found at 0
📊

Quick Reference

Here is a quick summary of useful functions to find substrings in PHP:

FunctionDescriptionReturn Value
strpos($haystack, $needle)Finds first position of substringPosition (int) or false
strrpos($haystack, $needle)Finds last position of substringPosition (int) or false
stripos($haystack, $needle)Case-insensitive first positionPosition (int) or false
strripos($haystack, $needle)Case-insensitive last positionPosition (int) or false
str_contains($haystack, $needle) (PHP 8+)Checks if substring existstrue or false

Key Takeaways

Use strpos() to find the position of a substring in a string in PHP.
Check strpos() result with strict comparison (=== false) to avoid errors.
If strpos() returns 0, it means the substring is at the start of the string.
Use str_contains() in PHP 8+ for a simple true/false substring check.
Remember strpos() is case-sensitive; use stripos() for case-insensitive search.