PHP str_replace () function
Examples
The string "! Hello world" characters "world" replaced by "Peter":
<?php
echo str_replace("world","Peter","Hello world!");
?>
echo str_replace("world","Peter","Hello world!");
?>
Running instance »
Definition and Usage
str_replace () function replaces some characters in the string (case-sensitive).
This function must follow these rules:
- If the search string is an array, it returns an array.
- If the search string is an array, then it will find and replace each element in the array.
- If you need to find and replace an array, and the need to perform replacement of the elements is less than the number of elements to look for, then the extra elements will be replaced with an empty string.
- If an array is to find, but only for a string to be replaced, then the replacement string values will all find work.
Note: This function is case-sensitive.Use str_ireplace () function performs a case-insensitive search.
Note: This function is binary safe.
grammar
str_replace( find,replace,string,count )
参数 | 描述 |
---|---|
find | 必需。规定要查找的值。 |
replace | 必需。规定替换find中的值的值。 |
string | 必需。规定被搜索的字符串。 |
count | 可选。一个变量,对替换数进行计数。 |
technical details
return value: | Returns a string or an array with a replacement value. |
---|---|
PHP version: | 4+ |
Update log: | In PHP 5.0, add the count parameter. Prior to PHP 4.3.3, find and replace the function parameters are an array will be in trouble, cause when empty find the index did not change in the internal pointer to replace the array is ignored. The new version will not have this problem. Since PHP 4.0.5, most parameters can be an array. |
More examples
Example 1
With the use of arrays and count variable str_replace () function:
<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo "Replacements: $i";
?>
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo "Replacements: $i";
?>
Running instance »
Example 2
Using the element needs to be replaced with a less than look to the elements of str_replace () function:
<?php
$find = array("Hello","world");
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_replace($find,$replace,$arr));
?>
$find = array("Hello","world");
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_replace($find,$replace,$arr));
?>
Running instance »
PHP String Reference