【问题标题】:Find all matches between delimeters查找分隔符之间的所有匹配项
【发布时间】:2018-12-22 10:24:40
【问题描述】:

如何替换分隔符之间的所有<p> 标签?我的文字是

<p>other text...</p>
<p>other text...</p>
``text text...</p>
<p>text text...</p>
<p>text text ...``
<p>other text...</p>
<p>other text...</p>
``text text...</p>
<p>text text...</p>
<p>text text ...``
<p>other text...</p>
<p>other text...</p>
``text text...</p>
<p>text text...</p>
<p>text text ...``
<p>other text...</p>
<p>other text...</p>

我想匹配双反引号之间的所有&lt;p&gt; 标记(``此处的所有 p 标记``)作为分隔符,并用空字符串替换它们。如果使用正则表达式 /&lt;\/?p&gt;/i 在分隔符之外没有其他文本,我可以匹配 p 标签,但是如果在分隔符之外有文本和其他 p 标签,我如何匹配分隔符内的所有 p 标签。

【问题讨论】:

  • 尝试使用''\w*/&lt;\?p&gt;/i\w*''
  • @DigvijaysinhGohil 这个正则表达式根本不起作用。

标签: php regex preg-replace preg-replace-callback


【解决方案1】:

这是preg_replace_callback的工作:

$str = <<<EOD
<p>other text...</p>
<p>other text...</p>
``text text...</p>
<p>text text...</p>
<p>text text ...``
<p>other text...</p>
<p>other text...</p>
``text text...</p>
<p>text text...</p>
<p>text text ...``
<p>other text...</p>
<p>other text...</p>
``text text...</p>
<p>text text...</p>
<p>text text ...``
<p>other text...</p>
<p>other text...</p>
EOD;

$res = preg_replace_callback(
        '/``(?:(?!``).)*``/s', 
        function ($m) {
            return preg_replace('~</?p>~', '', $m[0]);
        },
        $str);
echo $res;

输出:

<p>other text...</p>
<p>other text...</p>
``text text...
text text...
text text ...``
<p>other text...</p>
<p>other text...</p>
``text text...
text text...
text text ...``
<p>other text...</p>
<p>other text...</p>
``text text...
text text...
text text ...``
<p>other text...</p>
<p>other text...</p>

【讨论】:

  • 您的代码适用于提供的文本,但有多个这样的块。我已经编辑了这个问题。使用此代码,我不想删除的 p 标签也被删除,即第一个和最后一个中的所有 p 标签都被删除。
  • 非常感谢您的精彩回答。实际上,我想出了一种方法来通过preg_replace()for 循环实现相同的结果,但这是最好的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多