PHP: how to cut an HTML tag, allowing <and>

Question:. How to remove HTML tags but allow the use of a larger and smaller character using PHP?

If I used the PHP function strip_tags() , it does not work:

 $string = '<p>if A > B</p>' echo strip_tags($string); // if AB // but I want to output "if A > B" 

UPDATE

Basically, I only want to allow / show plain text.

+4
source share
5 answers

You can use HTML Purifier , this will work not only with the <p>if A > B</p> example you wrote, but also with the <p>1<2 && 6>4</p> example written by DrJokepu .

When you enter <p>1<2 && 6>4</p> with valid elements set to none, the HTML cleaner will return the result: 1&lt;2 &amp;&amp; 6&gt;4 1&lt;2 &amp;&amp; 6&gt;4 .

+4
source

This will share everything that looks like an HTML tag.

 htmlentities(preg_replace('/<\\S.*?>/', '', $text)); 
0
source

Unfortunately, the easiest and most reliable way to get this working is to use an HTML parser. This one will do the trick. I do not know if it will process HTML snippets as described above. If not, the packaging must be trivial to make it acceptable HTML.

As others point out, parsing HTML with regex has a lot of rib cases to satisfy difficulties, as HTML is not regular.

0
source

Try this regex that I wrote: <([^>]? = "(\" | [^ "])?")? ([^>]? = '' (\ '' | [^ ''])? '')? [^>] *? >

0
source

Using:

 <p><?php echo htmlspecialchars("if A > B") ?></p> 

(of course, you can use any input instead of a literal string)

htmlspecialchars() converts text to HTML text, preserving < and > .

0
source

All Articles