PHP str_replace() Function
Example
Replace the characters "world" in the string "Hello world!" with "Peter":
Run Example »
Definition and Usage
The str_replace() function replaces some characters in a string (case-sensitive).
This function must follow these rules:
- If the search string is an array, then an array is returned.
- If the search string is an array, then it searches for and replaces each element in the array.
- If you need to search and replace in an array at the same time, and the number of elements to replace is less than the number of elements found, the extra elements are replaced with an empty string.
- If you search an array but replace with only a single string, the replacement string applies to all found values.
**Note:** This function is case-sensitive. Use the str_ireplace() function to perform a case-insensitive search.
**Note:** This function is binary-safe.
Syntax
str_replace(
find,replace,string,count
)
| Parameters | Description |
|---|---|
| find | Required. Specifies the value to find. |
| replace | Required. Specifies the replacement find value. |
| string | Required. Specifies the string to be searched. |
| count | Optional. A variable that counts the number of replacements. |
Technical Details
| Return Value: | Returns the string or array with replacement values. |
|---|---|
| PHP Version: | 4+ |
| Changelog: | In PHP 5.0, the count parameter was added. |
在 PHP 4.3.3 之前,该函数的 *find* 和 *replace* 参数都为数组时将会遇到麻烦,会引起空的 *find* 索引在内部指针没有更换到 *replace* 数组上时被忽略。新的版本不会有这个问题。
自 PHP 4.0.5 起,大多数参数可以是一个数组。 |
More examples
Example 1
Use the str_replace() function with arrays and a count variable:
Run Example »
Example 2
Use the str_replace() function with fewer elements to replace than elements found:
Run Example »
PHP String Reference Manual