2009-11-14 4 views
0

나는 str_replace를 가지고 있고, 내가하고 싶은 것은 배열에서 값을 가져 와서 "dog"라는 단어를 대체 할 다음 부분을 가져 간다. 그래서 기본적으로 나는 $ 문자열을 읽고 싶은 :PHP str_replace with for array from 루프

"오리가 고양이를 먹고 돼지가 침팬지를 먹었다"

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

답변

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

+0

D' oh. 문서를 너무 빨리 지나쳤습니다 ... – brianreavis

+0

제한을 사용하기 때문에 str_replace가 preg_replace로 바뀌 었습니다. 이제 "오리가 고양이를 먹었고 개가 침팬지를 먹었습니다". 두 번째 "개"= [ – David

1

for 루프의 첫 번째 반복 후에 $ string은 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

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

+0

효과가 있습니다. 첫 번째 루프 $ str = 오리가 고양이를 먹었고 개가 침팬지를 먹었습니다. 두 번째 루프 오리가 고양이를 먹고 돼지가 침팬지를 먹었습니다. – lemon

0

아직 substr_replace()를 사용하여 하나의 옵션

$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

;

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