str_replace() swaps one piece of text for another.
<?php
$text = "I love cats. Cats are great.";
echo str_replace("cats", "dogs", $text);
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
<?php
$text = "I love cats. Cats are great.";
echo str_ireplace("cats", "dogs", $text);
I love dogs. dogs are great.
Replace several things at once
Pass arrays for the search and replace values.
<?php
$text = "Red and green and blue";
echo str_replace(
["Red", "green", "blue"],
["Orange", "yellow", "purple"],
$text
);
Orange and yellow and purple
Count how many replacements happened
<?php
$count = 0;
$result = str_replace("a", "4", "banana", $count);
echo "$result ($count replacements)";
b4n4n4 (3 replacements)
Practical example: make a URL slug
<?php
$title = "My First Blog Post";
$slug = strtolower(str_replace(" ", "-", $title));
echo $slug;
my-first-blog-post
Replace part of a string by position
substr_replace() replaces by position instead of by text.
<?php
$card = "4111111111111111";
echo substr_replace($card, "************", 0, 12);
************1111
Swap many pairs: strtr()
strtr() replaces several pairs in one pass. It never replaces something it has already replaced.
<?php
echo strtr("Hi all", ["Hi" => "Hello", "all" => "everyone"]);
Hello everyone
Patterns need regex
preg_replace(), which works with regular expressions. JavaScript Regular Expressions explains the same pattern ideas.