2011-02-17 126 views
0

我有一个声明替换在PHP中做(使用str_replace或其他)。我有这样的句子:str_replace除两个标记之间的/ 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

有永远只有一个``部分? – 2011-02-17 11:55:08

回答

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

相关问题