CodeBlanks Logo Icon CodeBlanks

Replacing with str_replace()

PHP course · Beginner · Lesson 88/116

Learn to replace a substring in a string with str_replace().

Replacing with str_replace()

In PHP, you replace a substring with str_replace(). It takes three arguments: str_replace($search, $replace, $subject). $search is the text to find, $replace is the new text, and $subject is the string to search in. It replaces every match and returns a new string.

For example, str_replace('pen', 'book', 'pen buy') returns 'book buy'. The original string stays unchanged; you assign the result to a variable.

Several replacements at once

To replace several substrings in one call, you can pass arrays for $search and $replace. PHP pairs them in order: the first search value is replaced by the first replace value, the second by the second.

For example, str_replace(['red', 'blue'], ['green', 'yellow'], 'red and blue') returns 'green and yellow'. This is cleaner than calling the function twice.

Case sensitivity

str_replace() is case-sensitive. So 'PHP' and 'php' are not the same. If you want a replacement that ignores case, use str_ireplace(); the i stands for insensitive.

For example, str_replace('php', 'X', 'PHP 8.3') finds no match and returns the string unchanged. This is a detail to remember when you replace text that came from free user input.

Exercise Replace two words at once

Assign "Red car drives fast" to $text. Use str_replace() to assign $result with two changes: "Red" → "Blue" and "fast" → "slow". Pass the search and replace values as arrays. Then print it with echo $result;.

Show example solution
First assign $text, then write $result = str_replace([...], [...], $text); then add echo $result;
Example solution:
<?php
$text = "Red car drives fast";
$result = str_replace(["Red", "fast"], ["Blue", "slow"], $text);
echo $result;

Test yourself

  1. What does str_replace('a', 'e', 'banana') return?

    str_replace('a', 'e', 'banana')
    • benene
    • banana
    • benane
    • It errors
    Show answer

    benene — Correct. Every 'a' becomes 'e': 'banana' → 'benene'.

  2. Fix the typo

    $word = 'aple';
    $fixed = ____('aple', 'apple', $word);
    echo $fixed;
    Show answer
    $word = 'aple';
    $fixed = str_replace('aple', 'apple', $word);
    echo $fixed;
  3. What does str_replace('php', 'X', 'PHP 8.3 here') return?

    str_replace('php', 'X', 'PHP 8.3 here')
    • X 8.3 here
    • PHP 8.3 here
    • XHP 8.3 here
    • It errors
    Show answer

    PHP 8.3 here — Correct. str_replace is case-sensitive; 'PHP' does not match 'php'.

All lessons in Beginner