str_replace
Replaces all occurrences of a substring with another string.
Available since: PHP 4
Syntax
str_replace(
array|string $search,
array|string $replace,
string|array $subject,
int &$count = null
): string|arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $search | array|string | The value to look for. Pass an array to search for each of its elements. |
| $replace | array|string | The replacement. A string, or an array of replacements matching the $search elements. |
| $subject | string|array | The string or array of strings to search in. |
| $count | int | Optional. This variable receives the number of replacements performed. |
Return value
string|arrayA string or an array with the replacements applied.
Examples
A simple replacement:
<?php
echo str_replace('world', 'PHP', 'Hello, world!');Output:
Hello, PHP!Several replacements in one call:
<?php
echo str_replace(['a', 'b'], ['1', '2'], 'abc');Output:
12cCounting the replacements:
<?php
str_replace('o', '0', 'foo boo', $count);
echo $count;Output:
4Notes
The function is case-sensitive. Use str_ireplace() for a case-insensitive replacement.
See also
- str_contains — Checks whether a string contains a given substring.
- trim — Removes whitespace and other characters from both ends of a string.
Related recipes
In the tutorial
- Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.