在PHP中替换数组中的文本
我有一个PHP$aResults数组,包含数千个URL,如下所示:在PHP中替换数组中的文本,php,str-replace,Php,Str Replace,我有一个PHP$aResults数组,包含数千个URL,如下所示: Array ( [0] => http://test.com/server1/Image?img=nortel.jpg ) Array ( [1] => http://test.com/server1/Image?img=network.jpg ) http://test.com/server5/photo?img= 我需要替换每个url内的文本,并将服务器从server1替换为server5,将单词imag
Array ( [0] => http://test.com/server1/Image?img=nortel.jpg )
Array ( [1] => http://test.com/server1/Image?img=network.jpg )
http://test.com/server5/photo?img=
我需要替换每个url内的文本,并将服务器从server1替换为server5,将单词image替换为photo,因此每个url应如下所示:
Array ( [0] => http://test.com/server1/Image?img=nortel.jpg )
Array ( [1] => http://test.com/server1/Image?img=network.jpg )
http://test.com/server5/photo?img=
我如何做到这一点
我尝试了str_replace函数的一种变体,但我无法完成这项工作:
$sImgURL = $aResults[1][0];
$filter_url ='server1/Image';
$replace='server5/photo';
$filtered_url = str_replace($filter_url, $replace, $aResults);
print_r($aResults);
实现这一目标的最佳方式是什么?感谢($i=0;$i将您的值放入“查找”,将您的值放入“替换”数组
for ($i = 0; $i <= sizeof($aResults); $i++) {
$aResults[$i] = str_replace('server1/Image', 'server5/photo', $aResults[$i]);
}
$find = array('server1', 'Image');
$replace = array('server5', 'photo');
$newString = str_replace($find, $replace, $oldString);
可以使用数组映射和str替换函数:
<?php
$data = array(
0 => 'http://test.com/server1/Image?img=nortel.jpg' ,
1 => 'http://test.com/server1/Image?img=network.jpg',
2 => 'http://test.com/server1/Image?img=rk.jpg',
3 => 'http://test.com/server1/Image?img=nek.jpg'
);
function foo($val){
return str_replace(
array('server1','Image'),
array('server5','photo'),
$val
);
}
$res = array_map("foo",$data);
var_dump($res);
?>
使用
foreach
有什么问题?也许可以代替:print\r($aResults);
do:print\r($filtered\u url);
?!@Rizier123http://test.com/server5/photo?img=nortel.jpg不是OP要求的。$arr=str\u replace(“/server1/Image”、“/server5/Photo”、$arr);
不好?@Jessica如果OP想要一个满是:http://test.com/server5/photo?img=
然后他就可以做:array\u fill(0,count($currentArray),”http://test.com/server5/photo?img=“”;
…还可以接受数组,因此不需要循环!(而且这个循环甚至不能正确运行)当然,很好地发现,我忘记了它可以接受数组,这将是一个更干净的解决方案。另一方面,为什么循环不运行?只要$I++
是真的,你的循环就会运行!直到整数溢出,只要你不点击你调用的sizeof()
只是为了好玩。噢,语义学,好吧,我有两个参数搞错了哈,太晚了,我将交换它们:)告诉某人他们的代码不正确只有在你也说为什么绝对没有必要这样做时才有用str_replace()
还将数组作为参数。因此,所有这些函数调用都是不必要的。