PHP 8 reference · String Functions
PHP str_replace() Function
Replace every occurrence of a search string with a replacement. Accepts arrays to make several replacements at once.
PHP 8 Since 4.0
Syntax
str_replace(array|string $search, array|string $replace, string|array $subject, int &$count = null): string|array
Parameters
| Parameter | Description |
|---|---|
search |
The value to find, or an array of values. |
replace |
The replacement, or an array matched to search by position. |
subject |
The string (or array of strings) to search in. |
count optional |
Set to the number of replacements made. |
Return value
The string (or array) with replacements made.
Examples
<?php
echo str_replace("cat", "camel", "The cat sat on the cat mat"), "\n";
echo str_replace(" ", "-", "my blog post title"), "\n";
Output
The camel sat on the camel mat my-blog-post-title
<?php
$template = "Hello {name}, your order {id} has shipped.";
echo str_replace(["{name}", "{id}"], ["Ada", "#1042"], $template), "\n";
Output
Hello Ada, your order #1042 has shipped.
<?php
str_replace("o", "0", "foo boo", $count);
echo $count, "\n";
Output
4
Common mistakes
- It's case-sensitive; use
str_ireplace()to ignore case. - With arrays, replacements run in order, so a later rule can change the output of an earlier one.
strtr()replaces everything in one pass.
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
str.replace()· Pythonstring.replaceAll()· JavaScript
Related
str_ireplace()· Replace every occurrence of a search string, ignoring upper and lower case. Otherwise works like str_replace().substr_replace()· Replace part of a string, given a start position and length, with another string. Also inserts text or masks digits.strtr()· Translate characters, or replace substrings in one pass using an array of from => to pairs. Longest keys match first.- PHP Strings · tutorial