Dav*_*vid 0 php arrays loops replace for-loop
好吧,我有一个str_replace,我想做的是从数组中获取值,然后用下一个部分替换"dog"一词.所以基本上我想要$ string读取:
"鸭子吃了猫,猪吃了黑猩猩"
<?php
$string = 'The dog ate the cat and the dog ate the chimp';
$array = array('duck','pig');
for($i=0;$i<count($array);$i++) {
$string = str_replace("dog",$array[$i],$string);
}
echo $string;
?>
Run Code Online (Sandbox Code Playgroud)
这段代码只返回:
"鸭子吃了猫,鸭子吃了黑猩猩"
我尝试了几件事,但没有任何作用.有人有主意吗?
编辑:对不起之前的错误答案.这样就行了.不str_replace,不preg_replace,只是原始,快速的字符串搜索和拼接:
<?php
$string = 'The dog ate the cat and the dog ate the chimp';
$array = array('duck', 'pig');
$count = count($array);
$search = 'dog';
$searchlen = strlen($search);
$newstring = '';
$offset = 0;
for($i = 0; $i < $count; $i++) {
if (($pos = strpos($string, $search, $offset)) !== false){
$newstring .= substr($string, $offset, $pos-$offset) . $array[$i];
$offset = $pos + $searchlen;
}
}
$newstring .= substr($string, $offset);
echo $newstring;
?>
Run Code Online (Sandbox Code Playgroud)
ps在这个例子中没什么大不了的,但是你应该把它count()放在你的循环之外.有了它,它会在每次迭代时执行,并且比预先调用一次要慢.