且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何替换文本,除非它在PHP中的两个标记之间?

更新时间:2022-12-11 08:27:43

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