【问题标题】:PHP: Regex replace everything between to strings/HTML tagsPHP:正则表达式替换字符串/HTML标签之间的所有内容
【发布时间】:2018-02-09 17:17:40
【问题描述】:

我有以下文本,但希望从字符串中删除引号位,我正在使用以下正则表达式,但它给了我以下错误。

文本示例 1

<p>[quote]</p>
<p>[quote]</p>
<p>inner quote text</p>
<p>[/quote]</p>
<p>outer quote text</p>
<p>[/quote]</p>
<p>This is a test.</p>

文本示例 2

<p>[quote][quote]</p>
<p>inner quote text</p>
<p>[/quote]</p>
<p>outer quote text</p>
<p>[/quote]</p>
<p>This is a test.</p>

预期文本

<p>This is a test.</p>

正则表达式

preg_replace('/<p>\[quote\][\s\S]+?<p>\[\/quote\]<\/p>/', '', $string);

错误

Warning: preg_replace(): Compilation failed: missing terminating ] for character class at offset

我查看了Deleting text between two strings in php using preg_replace,它有所帮助,但我无法弄清楚,非常感谢任何帮助。

【问题讨论】:

  • 结果文本应该是什么?
  • 1.) 错误表明您没有在 ...[ 中转义 ...\&lt;p\&gt;[...2.) 您的示例文本包含 [quote 而不是 [quote]。进一步没有必要逃避&lt;,&gt;
  • @mrzasa,抱歉,现在更新了问题。
  • 这个工具将帮助你测试你的正则表达式(有很好的解释):regex101.com

标签: php regex


【解决方案1】:

您收到此错误的原因是您没有在正则表达式中转义开头的 [ 字符。请看我在下面标记的[

preg_replace('/\<p\>\[quote\]\<\/p\>[\s\S]+?\<p\>[\/quote\]\<\/p\>/', '', $string);
                                                 ^

这导致启动了一个尚未关闭的角色类。您应该像这样简单地转义这个左大括号:

preg_replace('/\<p\>\[quote\]\<\/p\>[\s\S]+?\<p\>\[\/quote\]\<\/p\>/', '', $string);

【讨论】:

    【解决方案2】:

    从 HTML 中提取文本很棘手,因此最好的选择是使用 Html2Text 之类的库。它是专门为此目的而构建的。

    https://github.com/mtibben/html2text

    使用作曲家安装:

    作曲家需要 html2text/html2text 基本用法:

    $html = new \Html2Text\Html2Text('<p>[quote</p>test piece of text<p>[/quote]</p>This is a test.');
    
    echo $html->getText();  // test piece of text This is a test.
    

    或者你可以简单地使用函数 PHP strip_tags

    string strip_tags (string $str [, string $allowable_tags])

    http://php.net/strip_tags

    echo str_replace("[/quote]","",str_replace("[quote","",strip_tags("<p>
    [quote</p>
    test piece of text
    <p>[/quote]</p>
    This is a test.")));
    

    【讨论】:

      猜你喜欢
      • 2018-05-26
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-14
      相关资源
      最近更新 更多