Home  >  Article  >  Backend Development  >  Replacement vulnerability of php str_replace_PHP tutorial

Replacement vulnerability of php str_replace_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:53:461039browse

Definition and Usage
str_replace() function uses a string to replace other characters in a string.

Syntax
str_replace(find,replace,string,count)

Parameter Description
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.

Tips and Notes
Note: This function is case sensitive. Please use str_ireplace() to perform a case-insensitive search.

Note: This function is binary safe.

Example 1

Copy code The code is as follows:

echo str_replace("world","John","Hello world!");
?>

Output:

Hello John!

Example 2
In this example, we will demonstrate the str_replace() function with an array and count variable:
Copy code The code is as follows:

$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 The code is as follows:

$find = array("Hello","world");
$replace = array("B");
$arr = array("Hello","world", "!");
print_r(str_replace($find,$replace,$arr));
?>

输出:

Array
(
[0] => B
[1] =>
[2] => !
)


漏洞相关函数:


$arr1 = 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'
);
$arr2 = Array(
'http://localhost/root/ups/af48056fc4.jpg',
'http://localhost/root/ups/cf33240aa3.jpg',
'http://localhost/root/ups/c30e40419b.jpg'
);
$data = '


';
$data = str_replace($arr1,$arr2,$data);
var_dump($data);
?>

替换后的结果是:


string(169) ""str_replace 函数的声明大概是这样: str_replace($search, $replace, $input[,&$count]), 比如在对一个字符串进行替换操作, $input 就是源字符串(称为数据源). 这很不合理,因为它把数据源放在第3位, 而 str_pos, strtok, str_repeat 等等函数都是把数据源放在第1位.也就是说str_replace并没有替换掉数组中相对应的字符串,而是把数组中的第一个替换,然后把相同的字符串后多余的合并。

解决办法:
function strrplace($arr1,$arr2,$data){ 
if(is_array($arr1)) {  
foreach($arr1 as $key => $value)  {
   $data = str_replace_once($value, $arr2[$key], $data);
  } } 
return $data;
}
function str_replace_once($needle, $replace, $data) //替换第一次
{
$pos = strpos($data, $needle);
if ($pos === false) {
return $data; 
}
return substr_replace($data, $replace, $pos, strlen($needle));

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/318675.htmlTechArticle定义和用法 str_replace() 函数使用一个字符串替换字符串中的另一些字符。 语法 str_replace(find,replace,string,count) 参数 描述 find 必需。规定要查...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn