In PHP, strpos()
is a built-in function used to find the position of the first occurrence of a substring inside another string.
🔹 Syntax:
strpos(string $haystack, mixed $needle, int $offset = 0): int|false
- $haystack: The main string you want to search in.
- $needle: The substring you're looking for.
- $offset (optional): Start searching from this position.
- Returns:
- The position (0-based index) of the first occurrence of
$needle
.
false
if $needle
is not found.
✅ Basic Example:
<?php
$text = "Hello, world!";
$pos = strpos($text, "world");
if ($pos !== false) {
echo "Found at position: $pos"; // Output: Found at position: 7
} else {
echo "Not found";
}
?>
Notice: ===
is used instead of ==
to strictly check for false
(since position 0
is valid).
🔍 Example with Offset:
<?php
$text = "I love PHP. PHP is great!";
$pos = strpos($text, "PHP", 10);
echo $pos; // Output: 15 (the second occurrence)
?>
❌ Not Found Example:
<?php
$text = "Learning Laravel!";
$pos = strpos($text, "PHP");
if ($pos === false) {
echo "Not found"; // Output: Not found
}
?>
⚠️ Common Mistake:
$pos = strpos("PHP is cool", "PHP");
if ($pos) {
echo "Found"; // ❌ Won't echo because 0 == false
}
// Always use !== false to avoid this trap!
🎯 Use Case: Check if a string contains another string
function contains($text, $keyword) {
return strpos($text, $keyword) !== false;
}
echo contains("Laravel is awesome", "awesome") ? "Yes" : "No"; // Output: Yes