How to replace text except when it's between two tags in PHP?
Solution 1:
If the string is small, why not use explode()
to explode it at the tags,
and replace the strings in required fragments, and then rejoin it ?
Or try 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> ....*/
?>
See it here: http://codepad.org/T5o3shB4