3

How do I replace all <p> tags between delimiters? My text is

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

I want to match all <p> tags between double backticks (``all p tags here``) as delimiters and replace them with empty string. I could match p tags if there is no other text outside delimiters using regex /<\/?p>/i but how can I match all p tags inside delimiters if there is text and other p tags outside them.

Toto
  • 89,455
  • 62
  • 89
  • 125
loneFinder
  • 33
  • 3

1 Answers1

1

This is a job for 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;

Output:

<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>
Toto
  • 89,455
  • 62
  • 89
  • 125
  • Your code works for the text provided but there are multiple such blocks. I've edited the question. With this code the p tags I don't want to remove are also removed i.e. the all p tags from the first `` and last `` are removed. – loneFinder Jul 14 '18 at 11:10
  • Thank you very much for this amazing answer. Actually I figured out a way to achieve the same result by `preg_replace()` and a `for` loop but this is the best solution. – loneFinder Jul 14 '18 at 14:03