Php 替换html标记之间的单词

Php 替换html标记之间的单词,php,regex,replace,Php,Regex,Replace,我正在尝试获取两个符号或HTML标记之间的文本,然后在该HTML标记中查找所有单词“sun”并将其替换为“moon”,或者如果标记中的文本不包含任何搜索:()(.*)sun(.*)(.*) 替换为:\1moon\4这可能应该通过使用注释中提到的HTML解析器来完成。如果您想使用正则表达式,我会使用(使用>=PHP5.3) $text=preg\u replace\u回调('~\K.*(?=)~s',函数($m){ 返回preg_replace(['~\bsun\b~i'、'~']、[“moon”

我正在尝试获取两个符号或HTML标记之间的文本,然后在该HTML标记中查找所有单词“sun”并将其替换为“moon”,或者如果标记中的文本不包含任何
搜索:
()(.*)sun(.*)(.*)


替换为:
\1moon\4

这可能应该通过使用注释中提到的HTML解析器来完成。如果您想使用正则表达式,我会使用(使用>=PHP5.3)

$text=preg\u replace\u回调('~\K.*(?=)~s',函数($m){
返回preg_replace(['~\bsun\b~i'、'~']、[“moon”、“”、“&rt;”]、$m[0]);
}美元文本);
-没有匿名功能:

function rep_tag ($m) {
  return preg_replace(['~\bsun\b~i','~<~','~>~'], ["moon","&lt;","&rt;"], $m[0]);
}

$text = preg_replace_callback('~<tag>\K.*?(?=</tag>)~s', 'rep_tag', $text);
功能代表标签($m){
返回preg_replace(['~\bsun\b~i'、'~']、[“moon”、“”、“&rt;”]、$m[0]);
}
$text=preg\u replace\u回调('~\K.*(?=)~s','rep\u tag',$text);

您应该研究PHP解析HTML的方法。不要使用正则表达式,因为它不适合HTML之类的非规则内容。但是最好使用HTML解析器。谢谢。但是我还想替换
这是第一次提到-如果这是一个要求,请将其包含在您的问题中,谢谢我不知道

<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>
$str = "<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>";
$result = preg_replace("/sun(?=[^<]*<\/tag>)/", "moon", $str);
<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>
$text = preg_replace_callback('~<tag>\K.*?(?=</tag>)~s', function ($m) {
  return preg_replace(['~\bsun\b~i','~<~','~>~'], ["moon","&lt;","&rt;"], $m[0]);
}, $text);
function rep_tag ($m) {
  return preg_replace(['~\bsun\b~i','~<~','~>~'], ["moon","&lt;","&rt;"], $m[0]);
}

$text = preg_replace_callback('~<tag>\K.*?(?=</tag>)~s', 'rep_tag', $text);