PHP str_replace Tutorial: Replace Strings the Easy Way

The PHP str_replace function is the simplest and most commonly used tool for performing PHP string replace operations. If you’ve ever asked how to replace a string in PHP, PHP str_replace is the first function to learn. In this guide we cover syntax, common patterns, performance considerations, and practical examples you can paste into your projects.


Table of Contents

What is PHP str_replace?

PHP str_replace is a built-in function that replaces all occurrences of a search string with a replacement in the given subject (string or array). It’s designed for straightforward text substitutions and is an essential part of any PHP developer’s toolkit for PHP string replace tasks.

Basic syntax

PHP
$newString = str_replace($search, $replace, $subject, $count);
  • $search — string or array of strings to search for. This is the needle searched for in the haystack. An array may be used to search for multiple needles.
  • $replace — string or array of replacement values. It replaces the $search value. An array can be used to assign multiple replacements.
  • $subject — string or array of strings to perform replacements on. This is the haystack in which the needle or needles are searched for.
  • $count (optional) — if passed, will contain the number of replacements performed.
  • Return value: str_replace() returns a copy of the input $subject string or array with the values replaced.

Simple example: Replace a Word with PHP str_replace

Here’s a minimal example showing how to replace one word with another — an answer for anyone asking how to replace a string in PHP quickly. In this example, the word “world” in the string “Hello, world!” is replaced by the string “PHP”. As a result, the string returned is “Hello, PHP!”.

PHP
$original = "Hello, world!";
$result = str_replace("world", "PHP", $original);
echo $result; // Hello, PHP!

Replace Multiple Values: PHP str_replace with Arrays

PHP str_replace supports arrays for both search and replace. This makes it ideal when you need multiple substitutions in one pass. In the following example an array of three strings is searched for and each one is replaced by the corresponding value in the replace array.

PHP
$text = "red green blue";
$search = ["red", "green", "blue"];
$replace = ["#f00", "#0f0", "#00f"];
$converted = str_replace($search, $replace, $text);
echo $converted; // #f00 #0f0 #00f

This approach is much cleaner than chaining multiple str_replace calls for a series of replacements.


Case-insensitive Alternative

If your replacement must ignore case, use str_ireplace. It follows the same parameter order and behavior but matches case-insensitively — useful for many PHP string replace scenarios where input casing varies.

PHP
$result = str_ireplace("Hello", "Hi", "hello world");
echo $result; // Hi world

Replacing in Arrays and Counting Replacements

PHP str_replace can accept arrays as the $subject and can return how many replacements were made via the optional $count parameter. In the following str_replace example code, the $subjects array is the haystack in which the needle is searched for. The needle searched for is the “apple” string. This string is replaced by “pear” each time it is found in the array. In addition to replacing parts of strings in an array of strings, this example counts the number of replacements, which is 2.

PHP
$subjects = ["apple pie", "apple tart"];
$count = 0;
//                     needle   replace haystack
$results = str_replace("apple", "pear", $subjects, $count);
print_r($results); // ["pear pie", "pear tart"]
echo $count; // 2

Performance Tips when Using PHP str_replace

  • For a small number of replacements, PHP str_replace is extremely fast and efficient.
  • When performing many replacements on very large strings, prefer a single call with arrays to avoid repeated scanning.
  • Avoid repetitive regex-based replacements (like preg_replace) when a plain string replace would suffice — PHP str_replace is faster for literal replacements.
  • If replacement logic needs context (like whole words only), consider preg_replace with word boundaries instead.

Common Pitfalls and How to Avoid Them

  • Order-dependent replacements: If replacements overlap, array order matters. For example, replacing “cat” then “caterpillar” may produce unexpected results. Plan your array order or use unique placeholders.
  • Binary or multibyte data: For multibyte character encodings, str_replace works byte-wise. For character-aware replacements, ensure your data is encoded properly (UTF-8) and test thoroughly.
  • Unintended partial matches: To replace whole words only, use regular expressions with preg_replace('/\bword\b/', 'replacement', $text).

Real-world Example: Sanitize User Input with PHP str_replace

A lightweight sanitizer to normalize line endings and remove problematic characters:

PHP
$input = $_POST['message'] ?? '';
$search = ["\r\n", "\r", "\0"];
$replace = ["\n", "\n", ''];
$clean = str_replace($search, $replace, $input);

This is a practical answer to developers asking how to replace a string in PHP when normalizing text.


When to Use PHP str_replace vs preg_replace

Use PHP str_replace when replacing literal strings (no patterns). Reach for preg_replace when you need pattern matching, lookarounds, or word boundaries. For case-insensitive literal replacement, str_ireplace is the better choice.


FAQ

What does PHP str_replace do?

str_replace in PHP replaces all occurrences of the search string with the replacement string in the subject provided. It can work with strings or arrays.

How do I replace multiple strings at once?

Pass arrays for $search and $replace to PHP str_replace. The function will map each search element to the corresponding replace element.

How do I perform a case-insensitive replace?

Use str_ireplace for case-insensitive replacements; syntax mirrors str_replace.

How can I count how many replacements were made?

Provide a fourth argument (by reference) to PHP str_replace. After the call, it will contain the integer number of replacements.

Is PHP str_replace safe for multibyte text?

PHP str_replace performs byte-wise replacements. It works fine with UTF-8 as long as you treat strings consistently, but be cautious when replacing by character positions — use multibyte string functions if you need character-aware operations.


Conclusion

PHP str_replace is the go-to for straightforward PHP string replace tasks and answers the common question how to replace a string in PHP efficiently. Use arrays for bulk replacements, choose str_ireplace for case-insensitive needs, and prefer preg_replace only when patterns are required. With these patterns and examples you’re ready to apply str_replace in PHP confidently in your projects.

PHP documentation reference: https://www.php.net/manual/en/function.str-replace.php

See our PHP Programming category for more PHP tutorials and articles.