Definitions and Usage
The Str_replace () function replaces some other characters in a string with a string.
Grammar
Str_replace (Find,replace,string,count)
Parameter description
Find required. Specify the value to find.
Replace Required. Specify a value that replaces the value in Find.
String required. Specify the string to be searched for.
Count is optional. A variable that counts the number of replacements.
Tips and Comments
Note: This function is sensitive to case sensitivity. Use Str_ireplace () to perform a search that is not case sensitive.
Note: This function is binary safe.
Example 1
Copy Code code as follows:
<?php
echo Str_replace ("World", "John", "Hello world!");
?>
Output:
Hello john!
Example 2
In this example, we will demonstrate the str_replace () function with array and count variables:
Copy Code code as follows:
<?php
$arr = Array ("Blue", "Red", "green", "yellow");
Print_r (Str_replace ("Red", "pink", $arr, $i));
echo "Replacements: $i";
?>
Output:
Array
(
[0] => Blue
[1] => Pink
[2] => Green
[3] => Yellow
)
Replacements:1
Example 3
Copy Code code as follows:
<?php
$find = Array ("Hello", "World");
$replace = Array ("B");
$arr = Array ("Hello", "World", "!");
Print_r (Str_replace ($find, $replace, $arr));
?>
Output:
Array
(
[0] => B
[1] =>
[2] =>!
)
Vulnerability related functions:
<?php
$arr 1 = Array (
' http://img.jb51.net/img/offer/29/24/70/20/29247020 ',
' Http://img.jb51.net/img/offer/29/24/70/20/29247020-1 ',
' Http://img.jb51.net/img/offer/29/24/70/20/29247020-2 '
);
$arr 2 = Array (
' Http://localhost/root/ups/af48056fc4.jpg ',
' Http://localhost/root/ups/cf33240aa3.jpg ',
' Http://localhost/root/ups/c30e40419b.jpg '
);
$data = '
;
$data = Str_replace ($arr 1, $arr 2, $data);
Var_dump ($data);
?>
The result of the replacement is:
String (169) "
Solution:
function Strrplace ($arr 1, $arr 2, $data) {
if (Is_array ($arr 1)) {
foreach ($arr 1 as $key => $value) {
$data = Str_replace_once ($value, $arr 2[$key], $data);
} }
return $data;
}
function Str_replace_once ($needle, $replace, $data)//replace for the first time
{
$pos = Strpos ($data, $needle);
if ($pos = = False) {
return $data;
}
Return Substr_replace ($data, $replace, $pos, strlen ($needle));
}