PHP provides powerful string search functions to locate substrings, find their positions, and count their occurrences. These functions support both case-sensitive and case-insensitive searches.
strpos() – First occurrence (case-sensitive)stripos() – First occurrence (case-insensitive)strrpos() – Last occurrence (case-sensitive)strripos() – Last occurrence (case-insensitive)substr_count() – Count occurrencesThese functions return either a numeric position (starting from 0) or false if the substring is not found. Always use strict comparison when checking results.
// Find the position of a substring (case-sensitive)
<?php
$string = "Hello World";
$position = strpos($string, "World");
echo $position;
?>
The output is 6 because the word "World" starts at index 6 in the string.
// Case-insensitive substring search
<?php
$string = "Hello World";
$position = stripos($string, "world");
echo $position;
?>
// Find the last occurrence of a substring
<?php
$string = "Hello World World";
$position = strrpos($string, "World");
echo $position;
?>
// Count how many times a substring appears
<?php
$string = "Hello World World";
$count = substr_count($string, "World");
echo $count;
?>
Imagine highlighting every occurrence of a word in a paragraph. PHP string search functions help you detect positions and counts, which can then be used to dynamically highlight or extract content.
=== false when checking strpos() resultssubstr_count() for fast frequency checks