如果字符串很小,为什么不使用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