【问题标题】:Preg_replace not deleting text in between found tags [duplicate]Preg_replace 不删除找到的标签之间的文本[重复]
【发布时间】:2019-06-05 12:16:10
【问题描述】:

我正在尝试使用 preg_replace 从字符串中删除所有标题。它是 wordpress 摘录功能的一部分,删除帖子正文中的所有 <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 似乎并没有删除标题标签。

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

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

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

"&lt;p&gt;Here is some info.&lt;/p&gt;&lt;h2&gt;A new section&lt;/h2&gt;&lt;p&gt;Here is some more info.&lt;/p&gt;"

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

【问题讨论】:

  • 也许preg_replace($regex, '$1', $text); ?
  • 不,那也没用。我很确定我的整个 preg_replace 实际上由于某种原因失败了。当我将其设置为 $text = preg_replace ($regex, '', $text); 时,我什么也得不到

标签: php regex wordpress preg-replace


【解决方案1】:

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

$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 警告

【讨论】:

  • 警告来自没有正则表达式分隔符,这是您答案中的井号(仅用于澄清)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 2020-07-08
  • 2013-12-01
  • 2011-04-21
  • 2018-05-22
  • 2012-03-12
相关资源
最近更新 更多