How to replace text except when it's between two tags in PHP?
I have a statement replacement to do in php (using str_replace
or something else). I have this sentence:
the sun is yellow when the <wrong>red sun is not 开发者_运维问答yellow</wrong>
I want this:
the apple is yellow when the <wrong>red sun is not yellow</wrong>
So I need to replace a word, except between two specific tags (<wrong
and </wrong>
). How to do that with str_replace
or using a regex?
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
the difference is sun -> apple in the second word. for that example str_replace('sun', 'apple', $text, 1) will do just the first one
精彩评论