2011-02-17 2 views
0

나는 php에서 수행 할 진술 대체를 가지고 있습니다 (str_replace 또는 다른 것을 사용). str_replace except/else 두 태그 사이

"the sun is yellow when the <wrong>red sun is not yellow</wrong>"

내가이 원하는 :

"the apple is yellow when the <wrong>red sun is not yellow</wrong>"

그래서 나는 두 가지 특정 태그 (<wrong</wrong>) 사이를 제외하고, 단어를 교체 할 필요가 나는이 문장이있다. str_replace 또는 정규식을 사용하여이를 수행하는 방법?

좀 더 힘들지 않습니까? 나는 이미 많은 시간 동안 수색했다 ... 아무 단서 ... 어떤 생각? 솔루션이나 단서 또는

+0

항상 한''부분이 있습니까? –

답변

0

의 차이를 도움을

덕분에 일입니다 -> 두 번째 단어에 사과. 그 예를 들면 않는 str_replace에 대한 ('태양', '사과', $ 텍스트 1) 문자열이 작은 경우 바로 첫 번째

1

이, 왜, 태그에 그것을 폭발 explode()을 사용합니까 및 문자열을 대체합니다 필요한 단편에 넣은 다음 다시 합치면됩니까? 또는 DOMDocument를 시도 :

<?php 

$str = "the sun is yellow when the <wrong> This is also red sun not yellow red sun is not yellow some words </wrong> and here is 
yellow sun outside <wrong> , now yellow sun inside </wrong>"; 

$origArr = array("sun"); 
$replaceArr = array("apple"); 
$str = str_replace($origArr,$replaceArr,$str); 

$domElem = new DOMDocument(); 
$domElem->loadXML("<temp_tag>".$str."</temp_tag>"); 

$nodes = $domElem->getElementsByTagName('wrong'); 


$index = 0; 
while($nodes->item($index)->nodeValue) 
    { 
    $nodes->item($index)->nodeValue = str_replace($replaceArr,$origArr,$nodes->item($index)->nodeValue); 
    $index++; 
    } 

echo $domElem->saveHTML(); 

/* remove the <temp_tags> ....*/ 

?> 

는 여기를 참조하십시오 http://codepad.org/T5o3shB4