PHP code to clear the HTML tags in the string

  • 2020-03-31 21:17:09
  • OfStack

This article introduced PHP to clearing HTML tags from strings
There are two ways to filter all the HTML tags in a string. One is to write our own function with regular filters, and the other is to use PHP's own function strip_tags.

 
function clear_html_label($html) 
{ 
$search = array ("'<script[^>]*?>.*?</script>'si", "'<[/!]*?[^<>]*?>'si", "'([rn])[s]+'", "'&(quot|#34);'i", "'&(amp|#38);'i", "'&(lt|#60);'i", "'&(gt|#62);'i", "'&(nbsp|#160);'i", "'&(iexcl|#161);'i", "'&(cent|#162);'i", "'&(pound|#163);'i", "'&(copy|#169);'i", "'&#(d+);'e"); 
$replace = array ("", "", "1", """, "&", "<", ">", " ", chr(161), chr(162), chr(163), chr(169), "chr(1)"); 

return preg_replace($search, $replace, $html); 
} 

//Application instance

$string ='aaa<br /> <script>fdsafsa'; 
echo clear_html_label($string);//aaa fdsafsa 

//Using PHP's built-in strip_tags(); www.zzarea.com
echo strip_tags($string);//aaa fdsafsa 


Summing up,
The above two functions yield exactly the same results, a user-defined filter for all HTML functions and a built-in PHP function, but PHP's strip_tags() function is certainly much higher in terms of efficiency. At least why don't I say more.

Related articles: