好的,我有一个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;
?>
此代码只返回:
“鸭子吃了猫,鸭子吃了黑猩猩”我尝试了几件事,但没有任何作用。有人有什么想法吗?
答案 0 :(得分:5)
修改:对于之前的错误答案,我们深表歉意。这样就行了。没有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;
?>
P.S。在这个例子中没什么大不了的,但你应该把count()
放在你的循环之外。有了它,它会在每次迭代时执行,并且比预先调用它一样慢。
答案 1 :(得分:2)
<?php
$string = 'The dog ate the cat and the dog ate the chimp';
$array = array('duck', 'pig');
$count = count($array);
for($i = 0; $i < $count; $i++) {
$string = preg_replace('/dog/', $array[$i], $string, 1);
}
echo $string;
?>
鸭子吃了猫,猪吃了黑猩猩
答案 2 :(得分:1)
在你的for循环的第一次迭代之后,$ string将替换两个出现的dog with duck并且以下迭代将不会做任何事情。
我想不出更优雅的解决方法,我希望有更简单的方法:
<?php
$search = 'The dog ate the cat and the dog ate the chimp';
$replacements = array('duck','pig');
$matchCount = 0;
$replace = 'dog';
while(false !== strpos($search, $replace))
{
$replacement = $replacements[$matchCount % count($replacements)];
$search = preg_replace('/('.$replace.')/', $replacement, $search, 1);
$matchCount++;
}
echo $search;
答案 3 :(得分:0)
还有一个选项
$str = 'The dog ate the cat and the dog ate the chimp';
$rep = array('duck','pig');
echo preg_replace('/dog/e', 'array_shift($rep)', $str);
答案 4 :(得分:0)
使用substr_replace()
;
<?php
function str_replace_once($needle, $replace, $subject)
{
$pos = strpos($subject, $needle);
if ($pos !== false)
$subject = substr_replace($subject, $replace, $pos, strlen($needle));
return $subject;
}
$subject = 'The dog ate the cat and the dog ate the chimp';
$subject = str_replace_once('dog', 'duck', $subject);
$subject = str_replace_once('dog', 'pig', $subject);
echo $subject;
?>