Strip all tag except inside <Pre

42 Views Asked by At

I have a string.

$string = '<p>someText</p><li>someText</li><pre><p>someText</p></pre>';
I

want strip all tags except inside pre tag. for example output of $string is :

$string = 'someTextsomeText<pre><p>someText</p></pre>';

this is not working:

$string = strip_tags($string,<pre>);

1

There are 1 best solutions below

0
Anthony Bird On

Here is a solution - with an example string as:

$string = '<p>some Text First</p><li>some Text First</li><pre><p>someTextInside</p></pre><p>Some Text Last</p>';

Make pattern to find pre and contents within:

$pattern="/\<pre>(.*?)<\/pre>/";

Use preg_match to find patter:

$preSection = preg_match($pattern, $string, $matches);

Split into parts BEFORE pre and AFTER pre:

$parts = explode($matches[0], $string);

Strip Tags from content before pre and after pre and combine together to final string:

$final = strip_tags($parts[0]) . $matches[0] . strip_tags($parts[1]);

echo $final;

// RESULT: some Text Firstsome Text First<pre><p>someTextInside</p></pre>Some Text Last