Preg_replace 不删除找到的标签之间的文本

Preg_replace not deleting text in between found tags

我正在尝试使用 preg_replace 删除字符串中的所有标题。它是 wordpress 摘录功能的一部分,取出 post 的 body 内的所有 <h3>Title</h3> 标签,否则它们会打断段落流。

所以目标是在一个字符串中,例如

"<p>Here is some info.</p><h2>A new section</h2><p>Here is some more info.</p>"

我的输出字符串是

"<p>Here is some info.</p><p>Here is some more info.</p>"

我很确定我的正则表达式是正确的。但是 preg_replace 似乎并没有删除 header 标签。

    $regex = array (
            '\<h1[^]]*\>(.*?)\</h1\>',
            '\<h2[^]]*\>(.*?)\</h2\>',
            '\<h3[^]]*\>(.*?)\</h3\>',
            '\<h4[^]]*\>(.*?)\</h4\>',
            '\<h5[^]]*\>(.*?)\</h5\>',
            '\<h6[^]]*\>(.*?)\</h6\>'
            );

    preg_replace($regex, '', $text);

标签内的文字牢牢固定在原位,即。

"<p>Here is some info.</p><h2>A new section</h2><p>Here is some more info.</p>"

编辑:没有意识到我的查询缺少分隔符。与其他问题类似,但不会通过谷歌搜索 "delimiter" 错误找到它们,因为没有收到错误。由于当时无法访问 ftp,因此未在网站上启用 Php 错误报告。不得不通过 wordpress 主题编辑器进行简单的编辑。可以想象其他人也有同样的问题,这个问题可能是他们以后的相关参考。

您的示例代码没有收到任何警告吗? 以下按预期工作

$text = "<p>Here is some info.</p><h2>A new section</h2><p>Here is some more info.</p>";
$regex = array (
    '#\<h1[^]]*\>(.*?)\</h1\>#',
    '#\<h2[^]]*\>(.*?)\</h2\>#',
    '#\<h3[^]]*\>(.*?)\</h3\>#',
    '#\<h4[^]]*\>(.*?)\</h4\>#',
    '#\<h5[^]]*\>(.*?)\</h5\>#',
    '#\<h6[^]]*\>(.*?)\</h6\>#'
);

$replaced = preg_replace($regex, '', $text);

echo $text;
echo PHP_EOL;
echo $replaced;

编辑

检查您是否禁用了 php 警告