You often need to ask: “does this text contain that word?” PHP gives you simple functions for it.
Does it contain…? str_contains()
<?php
$sentence = "PHP makes web pages";
var_dump(str_contains($sentence, "web"));
var_dump(str_contains($sentence, "Java"));
bool(true)
bool(false)
str_contains() was added in PHP 8.0. On PHP 7 you had to write strpos(...) !== false.
Starts with / ends with
<?php
$file = "report-2026.pdf";
var_dump(str_starts_with($file, "report"));
var_dump(str_ends_with($file, ".pdf"));
var_dump(str_ends_with($file, ".docx"));
bool(true)
bool(true)
bool(false)
Where is it? strpos()
strpos() returns the position of the first match, counting from 0. It returns false when there is no match.
<?php
$email = "ravi@example.com";
echo strpos($email, "@");
4
The zero trap
If the match is at the very start, the position is 0, and 0 looks like false. Always compare with ===.
<?php
$pos = strpos("apple pie", "apple");
var_dump($pos);
var_dump($pos === false);
int(0)
bool(false)
Case-insensitive and last match
<?php
$text = "Hello hello HELLO";
echo stripos($text, "HELLO") . "\n"; // ignore case, first match
echo strrpos($text, "hello") . "\n"; // last match, case-sensitive
echo substr_count(strtolower($text), "hello");
0
6
3
All the search functions
| Function | Returns |
|---|---|
str_contains($h, $n) | true or false |
str_starts_with($h, $n) | true or false |
str_ends_with($h, $n) | true or false |
strpos($h, $n) | Position of first match, or false |
stripos($h, $n) | Same, ignoring case |
strrpos($h, $n) | Position of the last match |
substr_count($h, $n) | How many times it appears |
$h is the “haystack” (the text to search in), $n the “needle” (what to find). The haystack always comes first.
Use the simplest function
str_contains(). Use strpos() only when you need the position.