Skip to content

PHP Tutorial Strings

Replacing Text

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

str_replace() swaps one piece of text for another.

index.php
PHP
<?php
$text = "I love cats. Cats are great.";

echo str_replace("cats", "dogs", $text);
Output
OUTPUT
I love dogs. Cats are great.

The function takes search, replace and subject in that order. It replaces every match, but it is case-sensitive: Cats with a capital C was left alone.

Ignore case

index.php
PHP
<?php
$text = "I love cats. Cats are great.";

echo str_ireplace("cats", "dogs", $text);
Output
OUTPUT
I love dogs. dogs are great.

Replace several things at once

Pass arrays for the search and replace values.

index.php
PHP
<?php
$text = "Red and green and blue";

echo str_replace(
    ["Red", "green", "blue"],
    ["Orange", "yellow", "purple"],
    $text
);
Output
OUTPUT
Orange and yellow and purple

Count how many replacements happened

index.php
PHP
<?php
$count = 0;
$result = str_replace("a", "4", "banana", $count);

echo "$result ($count replacements)";
Output
OUTPUT
b4n4n4 (3 replacements)

Practical example: make a URL slug

index.php
PHP
<?php
$title = "My First Blog Post";

$slug = strtolower(str_replace(" ", "-", $title));

echo $slug;
Output
OUTPUT
my-first-blog-post

Replace part of a string by position

substr_replace() replaces by position instead of by text.

index.php
PHP
<?php
$card = "4111111111111111";

echo substr_replace($card, "************", 0, 12);
Output
OUTPUT
************1111

Swap many pairs: strtr()

strtr() replaces several pairs in one pass. It never replaces something it has already replaced.

index.php
PHP
<?php
echo strtr("Hi all", ["Hi" => "Hello", "all" => "everyone"]);
Output
OUTPUT
Hello everyone
info
Patterns need regex
If you need to replace “any digits” or “any whitespace”, use preg_replace(), which works with regular expressions. JavaScript Regular Expressions explains the same pattern ideas.