Skip to content

PHP Tutorial Strings

Searching Strings

Lesson 62 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

You often need to ask: “does this text contain that word?” PHP gives you simple functions for it.

Does it contain…? str_contains()

index.php
PHP
<?php
$sentence = "PHP makes web pages";

var_dump(str_contains($sentence, "web"));
var_dump(str_contains($sentence, "Java"));
Output
OUTPUT
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

index.php
PHP
<?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"));
Output
OUTPUT
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.

index.php
PHP
<?php
$email = "ravi@example.com";

echo strpos($email, "@");
Output
OUTPUT
4

The zero trap

If the match is at the very start, the position is 0, and 0 looks like false. Always compare with ===.

index.php
PHP
<?php
$pos = strpos("apple pie", "apple");

var_dump($pos);
var_dump($pos === false);
Output
OUTPUT
int(0)
bool(false)

Case-insensitive and last match

index.php
PHP
<?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");
Output
OUTPUT
0
6
3

All the search functions

FunctionReturns
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.

lightbulb
Use the simplest function
If you only need yes or no, use str_contains(). Use strpos() only when you need the position.