如何替换分隔符之间的所有<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>

我想将双反勾号(``ALL P TAGS HERE``)之间的所有<p>标记匹配为分隔符,并用空字符串替换它们。如果使用regex/<\/?p>/i分隔符之外没有其他文本,我可以匹配p标记,但是如果分隔符之外有文本和其他p标记,我如何匹配分隔符之内的所有p标记。

最佳答案

这是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>

关于php - 查找定界符之间的所有匹配项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51335269/

10-11 03:06