查找分隔符之间的所有匹配项

Posted

技术标签:

【中文标题】查找分隔符之间的所有匹配项【英文标题】: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 这个正则表达式根本不起作用。 【参考方案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 循环实现相同的结果,但这是最好的解决方案。

以上是关于查找分隔符之间的所有匹配项的主要内容,如果未能解决你的问题,请参考以下文章

Power Query - 循环提取分隔符之间的文本

Excel:查找所有匹配值并放在逗号分隔列表中?

SQL 查询以查找由字母分隔的重复项

JS中search查找某些内容,正则表达式|查找分隔的任何项

需要在 AG-Grid 过滤器中使用空格分隔值来返回每个匹配项

SQL IN 子句仅返回以逗号分隔的 ID 列表中具有第一个匹配项的行