PHP String Search & Replace
In this page:
Finding Substring Position
strpos() returns the numeric position of the first occurrence of a substring within a string, or false if it isn't found — a common pitfall is using == false instead of === false, since a match at position 0 is falsy under loose comparison.
Example: Finding Substring Position
<?php
$text = "Hello World";
$pos = strpos($text, "World");
if ($pos !== false) {
echo "Found at position $pos";
}
?>
Login to try C/C++/Java/PHP code in the editor
Basic String Replacement
str_contains() (PHP 8+) directly answers whether a substring exists anywhere inside a string as a clean boolean, replacing the older, more error-prone pattern of checking strpos() against false.
Example: Basic String Replacement
<?php
if (!function_exists('str_contains')) {
function str_contains($haystack, $needle) {
return strpos($haystack, $needle) !== false;
}
}
$text = "Hello World";
var_dump(str_contains($text, "World"));
?>
Login to try C/C++/Java/PHP code in the editor
Case-Insensitive Replacement
str_replace() swaps every occurrence of a target substring with a replacement, and accepts arrays for both arguments so you can perform several find-and-replace operations in a single call, such as stripping multiple unwanted characters at once.
Example: Case-Insensitive Replacement
<?php
$text = "The Quick Brown Fox";
echo str_replace(["Quick", "Brown"], ["Slow", "Red"], $text);
?>
Login to try C/C++/Java/PHP code in the editor
Searching Case-Insensitively
substr() extracts a portion of a string starting at a given index for an optional given length, which is how you'd pull out, say, the first 100 characters of a blog post to use as a preview excerpt.
Example: Searching Case-Insensitively
<?php
$post = "This is a long blog post about PHP arrays and functions.";
echo substr($post, 0, 20);
?>
Login to try C/C++/Java/PHP code in the editor
Replacing Portions by Index
str_ireplace() and stripos() are the case-insensitive counterparts of str_replace() and strpos(), useful when you need to find or replace text regardless of whether the user typed it in uppercase, lowercase, or mixed case.
Example: Replacing Portions by Index
<?php
$text = "Hello WORLD";
echo str_ireplace("world", "PHP", $text) . "\n";
var_dump(stripos($text, "world"));
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: