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

PHP String Search & Replace

Search and replace on strings is like the Find and Replace tool in a document. PHP can tell you where a word sits inside a sentence, or swap it for another word.
Syntax
php
$position = strpos($haystack, $needle);   // false if not found
str_contains($haystack, $needle);         // PHP 8+
$result = str_replace($search, $replace, $subject);

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
// Declare `$text`, set to "Hello World"
$text = "Hello World";
// Declare `$pos`, set to `strpos($text, "World")`
$pos = strpos($text, "World");
// Check whether `$pos !== false`
if ($pos !== false) {
    // Print "Found at position $pos" to the output
    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
// Check whether `!function_exists('str_contains')`
if (!function_exists('str_contains')) {
    // Define the function `str_contains` taking `$haystack`, `$needle`
    function str_contains($haystack, $needle) {
        // Return `strpos($haystack, $needle) !== false` from this function
        return strpos($haystack, $needle) !== false;
    }
}
// Declare `$text`, set to "Hello World"
$text = "Hello World";
// Print a detailed dump (with types) of `str_contains($text, "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
// Declare `$text`, set to "The Quick Brown Fox"
$text = "The Quick Brown Fox";
// Print `str_replace(["Quick", "Brown"], ["Slow", "Red"], $text)` to the output
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
// Declare `$post`, set to "This is a long blog post about PHP arrays and functions."
$post = "This is a long blog post about PHP arrays and functions.";
// Print `substr($post, 0, 20)` to the output
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
// Declare `$text`, set to "Hello WORLD"
$text = "Hello WORLD";
// Print `str_ireplace("world", "PHP", $text) . "\n"` to the output
echo str_ireplace("world", "PHP", $text) . "\n";
// Print a detailed dump (with types) of `stripos($text, "world")`
var_dump(stripos($text, "world"));
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Testing strpos($s, a) with if (strpos(...)), which is false when the match is at position 0; compare with !== false instead.
  2. Using str_replace and expecting it to change the original variable, when it returns a new string.
  3. Using str_replace and expecting it to ignore case, when you need str_ireplace for case-insensitive replacement.
Chapter Summary
  • Strings support escape characters, string functions, and formatting.
  • Heredoc and nowdoc handle longer text, and search and replace change text content.
  • Regular expressions match patterns in text.

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.