2009-11-14 70 views
0

好吧,我有一个str_replace,我想做的是从数组中取值,并采取下一块取代单词“狗”。所以基本上我想要的$字符串为:PHP str_replace与从循环阵列

“鸭子吃了猫和猪吃黑猩猩”

<?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

我猜你可以使用'strstr'和'substr_replace'的组合。 – mpen 2009-11-14 06:09:33

回答

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; 
?> 

附:在这个例子中没有什么大不了的,但你应该在你的循环之外保留count()。有了它,它就会在每次迭代中执行,并且比预先调用一次更慢。

+0

str_replace的第四个参数必须是一个变量,它将填充替换次数。不是你想要的。 – camomileCase 2009-11-14 05:57:55

+0

D'oh。通过文档太快... – brianreavis 2009-11-14 05:59:21

+0

我用preg_replace替换了str_replace,因为它使用了限制,现在我得到了“鸭子吃了猫,狗吃了黑猩猩”。它不会取代第二个“狗”= [ – David 2009-11-14 05:59:41

1

您的for循环$ string的第一次迭代之后,将用duck代替dog的两次出现,以下迭代将不会执行任何操作。

我想不出解决这个更优雅的方式,我希望有更简单的东西可能:

<?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; 
+0

哇嘿,至少它的作品,我今晚会过去,所以我完全理解它。 =]非常感谢! – David 2009-11-14 06:01:55

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; 
?> 

鸭子吃了猫和猪吃黑猩猩

+0

哦,我想我明白了,如果你在所有的陈述中保留了相同的变量“$ string”,我会假设它会起作用吗? – David 2009-11-14 06:29:33

+0

它会工作。第一圈$ str =鸭子吃了猫,狗吃了黑猩猩。第二圈鸭子吃了猫,猪吃了黑猩猩。 – lemon 2009-11-14 07:30:31

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); 
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; 
?>