How to Use str_replace in PHP: Simple String Replacement
Use
str_replace($search, $replace, $subject) in PHP to replace all occurrences of $search with $replace in the string $subject. It returns the modified string without changing the original.Syntax
The str_replace function has three main parts:
- $search: The text you want to find.
- $replace: The text you want to use instead.
- $subject: The string where the replacement happens.
It returns a new string with replacements done.
php
str_replace(string|array $search, string|array $replace, string|array $subject, int &$count = null): string|array
Example
This example shows how to replace the word "world" with "PHP" in a sentence.
php
<?php $text = "Hello world!"; $newText = str_replace("world", "PHP", $text); echo $newText; ?>
Output
Hello PHP!
Common Pitfalls
One common mistake is expecting str_replace to change the original string. It returns a new string instead, so you must save or use the returned value.
Also, if you use arrays for $search and $replace, make sure they match in size to avoid unexpected results.
php
<?php // Wrong: original string unchanged $text = "apple"; str_replace("a", "b", $text); echo $text; // outputs 'apple' // Right: save the result $text = "apple"; $text = str_replace("a", "b", $text); echo $text; // outputs 'bpple' ?>
Output
apple
bpple
Quick Reference
| Parameter | Description |
|---|---|
| $search | Text or array of texts to find |
| $replace | Text or array of texts to replace with |
| $subject | String or array of strings to search in |
| $count (optional) | Variable to store number of replacements made |
Key Takeaways
str_replace returns a new string with replacements; original string stays unchanged.
Use matching array sizes for $search and $replace to avoid unexpected results.
Always save or use the returned value from str_replace.
You can replace multiple different texts at once by passing arrays.
str_replace is case-sensitive; use str_ireplace for case-insensitive replacements.