I am trying to get texts between two symbols or HTML tags, then find and replace all the words 'sun' with 'moon' within that HTML tag or <
with <
. for example I have a $text
like below:
<body>
<p>
text text sun text text...
<tag> some text here sun some text here </tag>
text text sun text sun text...
<span>
<tag> text here sun text text sun text </tag>
<tag> sun text here sun text sun, sun </tag>
</span>
</p>
</body>
I would like to find all the sun
's between the <tag>...</tag>
tags and replace them with moon
so that the result will be:
<body>
<p>
text text sun text text...
<tag> some text here moon some text here </tag>
text text sun text sun text...
<span>
<tag> text here moon text text moon text </tag>
<tag> moon text here moon text moon, moon </tag>
</span>
</p>
</body>
I tried $text = str_replace("sun","moon",$text);
but this will replace all the matches in or out of the tags. Also tried preg_replace("/(<tag>)(.*?)sun(.*?)(<\/tag>)/", "$2 moon $3", $text);
it doesn't work as expected.