相关函数:
<?php
$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 = '
<img src="http://img.jb51.net/img/offer/29/24/70/20/29247020"/>
<img src="http://img.jb51.net/img/offer/29/24/70/20/29247020-1"/>
<img src="http://img.jb51.net/img/offer/29/24/70/20/29247020-2"/>';
$data = str_replace($arr1,$arr2,$data);
var_dump($data);
?>
替换后的结果是:
string(169) "<img src="http://localhost/root/ups/af48056fc4.jpg"/><img src="http://localhost/root/ups/af48056fc4.jpg-1"/><img src="http://localhost/root/ups/af48056fc4.jpg-2"/>"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));}
文章评论
共有 位脚本之家网友发表了评论我来说两句