Replace the character "world" with "Peter" in the string "Hello world!":
<?phpecho str_replace("world","Peter","Hello world!");?>The str_replace() function replaces some characters in a string (case sensitive).
The function must follow the following rules:
If the searched string is an array, then it will return an array.
If the string being searched is an array, then it will find and replace every element in the array.
If an array needs to be searched and replaced at the same time, and the elements to be replaced are less than the number of elements found, the excess elements will be replaced with empty strings.
If you search an array and replace only one string, the replacement string will apply to all found values.
Note: This function is case-sensitive. Please use the str_ireplace() function to perform a case-insensitive search.
Note: This function is binary safe.
str_replace( find,replace,string,count )
parameter | describe |
---|---|
find | Required. Specifies the value to look for. |
replace | Required. Specifies the value to replace the value in find . |
string | Required. Specifies the string to be searched for. |
count | Optional. A variable counting the number of substitutions. |
Return value: | Returns a string or array with replacement values. |
---|---|
PHP version: | 4+ |
Update log: | In PHP 5.0, the count parameter is added. Before PHP 4.3.3, this function would run into trouble when both its find and replace parameters were arrays, causing the empty find index to be ignored when the internal pointer was not replaced on the replace array. The new version won't have this problem. As of PHP 4.0.5, most parameters can be an array. |
Use str_replace() function with array and count variable:
<?php$arr = array("blue","red","green","yellow");print_r(str_replace("red","pink",$arr,$i));echo "Replacements: $ i";?>Use the str_replace() function with fewer elements to replace than found:
<?php$find = array("Hello","world");$replace = array("B");$arr = array("Hello","world","!");print_r(str_replace($ find,$replace,$arr));?>