← Back to PHP Course | Chapter 6: Strings | Lesson 8 of 8

PHP String Search & Replace

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
<?php
$text = "Hello World";
$pos = strpos($text, "World");
if ($pos !== false) {
    echo "Found at position $pos";
}
?>

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
<?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"));
?>

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
<?php
$text = "The Quick Brown Fox";
echo str_replace(["Quick", "Brown"], ["Slow", "Red"], $text);
?>

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
<?php
$post = "This is a long blog post about PHP arrays and functions.";
echo substr($post, 0, 20);
?>

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
<?php
$text = "Hello WORLD";
echo str_ireplace("world", "PHP", $text) . "\n";
var_dump(stripos($text, "world"));
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.