PHP Reference ยท String Functions
PHP str_replace() function
Reference for PHP str_replace(): replace all occurrences of a search string, arrays of search and replace values, the count argument and replacement order.
str_replace() replaces every occurrence of a search string with a replacement string. The search is case-sensitive and plain-text; for case-insensitive replacement use str_ireplace(), and for patterns use preg_replace().
Search and replace can be arrays, and the subject can be an array of strings too. When you pass arrays, replacements are applied one after another, which has consequences described below.
<?php echo str_replace("cat", "dog", "cat and cat"); // dog and dog echo str_replace(["a", "b"], ["1", "2"], "abc"); // 12c
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
str_replace( array|string $search, array|string $replace, string|array $subject, int &$count = null ): string|array
| Name | Description |
|---|---|
$search |
The value(s) to look for. |
$replace |
The replacement(s). If $search is an array and $replace is a string, that string is used for every search value. If both are arrays, values pair by position; missing replacements become empty strings. |
$subject |
The string or array of strings to search and modify. |
$count |
Optional by-reference variable that receives the total number of replacements made. |
Return value: a string (or an array if $subject is an array) with the replacements applied.
Errors: a TypeError is thrown when $search is a string but $replace is an array.
Usage notes
- Case-sensitive; use
str_ireplace()to ignore case. - Sequential replacement. With arrays, each search runs on the result of the previous one, so earlier replacements can be re-replaced. Use
strtr()with an array to avoid that. - All occurrences are replaced; there is no limit argument. For "first only" use
strpos()withsubstr_replace(), orpreg_replace()with a limit. - Not for security. Removing
<script>or../withstr_replace()can be bypassed (<scr<script>ipt>); use proper escaping such ashtmlspecialchars(). - Array subjects keep their keys, and non-string elements are converted to strings.
- Empty search string leaves the subject unchanged.
- Byte-wise, so it is safe for UTF-8 when search and replacement are UTF-8.
- The count is the total across all searches and all subjects.