PHP str_replace() Function
Example
Replace the string "world" in "Hello world!" with "Peter":
Definition and Usage
The str_replace() function replaces some characters with some other characters in a string (case-sensitive).
The function must follow these rules:
- If the search string is an array, it will return an array. 
- If the search string is an array, it will search and replace within each element of the array. 
- If you search and replace an array, and the number of elements to be replaced is less than the number of elements found, the extra elements will be replaced with an empty string. 
- If you search an array but only replace with a string, the replacement string will apply to all found values. 
Note: This function is case-sensitive. Use the str_ireplace() function for case-insensitive search.
Note: This function is binary-safe.
Syntax
| Parameter | Description | 
|---|---|
| find | Required. Specifies the value to find. | 
| replace | Required. Specifies the value to replace the value in find. | 
| string | Required. Specifies the string to be searched. | 
| count | Optional. A variable that counts the number of replacements. | 
Technical Details
| Return Value: | Returns a string or an array with replaced values. | 
|---|---|
| PHP Version: | 4+ | 
| --- | --- | 
| Changelog: | Added the countparameter in PHP 5.0. <br> <br>Before PHP 4.3.3, when bothfindandreplaceare arrays, this function would encounter problems. Emptyfindindexes would be ignored before the internal pointer was updated to thereplacearray. Newer versions do not have this issue. <br> <br>Since PHP 4.0.5, most parameters can be arrays. | 
| --- | --- | 
More Examples
Example 1
Using the str_replace() function with arrays and the count variable:
Example 2
Using the str_replace() function with fewer elements to replace than found: