How to Replace Text in a String in PHP Easily
In PHP, you can replace text in a string using the
str_replace function. It takes the text to find, the replacement text, and the original string, then returns a new string with replacements done.Syntax
The str_replace function replaces all occurrences of a search string with a replacement string in the given original string.
- search: The text you want to replace.
- replace: The text you want to use instead.
- subject: The original string where replacements happen.
- The function returns a new string with replacements applied.
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 simple string.
php
<?php $original = "Hello world!"; $replaced = str_replace("world", "PHP", $original); echo $replaced; ?>
Output
Hello PHP!
Common Pitfalls
One common mistake is expecting str_replace to change the original string directly. It does not modify the original string but returns a new one. Also, be careful when replacing overlapping or similar substrings, as replacements happen in one pass.
php
<?php // Wrong: expecting original string to change $original = "apple"; str_replace("a", "b", $original); echo $original; // still "apple" // Right: assign the result $original = "apple"; $modified = str_replace("a", "b", $original); echo $modified; // "bpple" ?>
Output
apple
bpple
Quick Reference
| Function | Purpose | Example Usage |
|---|---|---|
| str_replace | Replace all occurrences of a string | str_replace('cat', 'dog', 'cat and cat') |
| str_ireplace | Case-insensitive replace | str_ireplace('Cat', 'dog', 'Cat and cat') |
| preg_replace | Replace using regular expressions | preg_replace('/cat/i', 'dog', 'Cat and cat') |
Key Takeaways
Use str_replace to replace text in strings and assign the result to a variable.
str_replace does not change the original string but returns a new one.
For case-insensitive replacement, use str_ireplace.
For complex patterns, use preg_replace with regular expressions.
Always test your replacements to avoid unexpected results with similar substrings.