What is the best way to strip all html tags from a string?

Using PHP, specify a string such as: this is a <strong>string</strong> ; I need a function to cut ALL html tags so that the output is: this is a string . Any ideas? Thanks in advance.

+4
source share
4 answers

PHP has a built-in function that does exactly what you want: strip_tags

 $text = '<b>Hello</b> World'; print strip_tags($text); // outputs Hello World 

If you expect broken HTML, you will need to load it into a DOM parser and then extract the text.

+11
source

How about using strip_tags , which should only do the job?

For example (citing a document):

 <?php $text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>'; echo strip_tags($text); echo "\n"; 

will provide you with:

 Test paragraph. Other text 

Edit: but note that strip_tags does not confirm what you give it. This means that this code:

 $text = "this is <10 a test"; var_dump(strip_tags($text)); 

You'll get:

 string 'this is ' (length=8) 

(Everything after the thing similar to the original tag is deleted).

+5
source

strip_tags is the function you execute. Would you use it something like this

 $text = '<strong>Strong</strong>'; $text = strip_tags($text); // Now $text = 'Strong' 
+1
source

I believe this is slightly more efficient than strip_tags () , since strip_tags () will not block javascript or css:

 $search = array( "'<head[^>]*?>.*?</head>'si", "'<script[^>]*?>.*?</script>'si", "'<style[^>]*?>.*?</style>'si", ); $replace = array("","",""); $text = strip_tags(preg_replace($search, $replace, $html)); 
0
source

All Articles