We all know that the php strip_tags() function is used to filter out the html, php, and xml tags in the string. This function can only retain the desired html tags, But the specified html tag cannot be filtered out, so how to filter out the specified html tag? Today we will take you to a detailed introduction to strip_tags() in PHP to only filter a certain tag in the string!
php removes the specified html tags in the string. We cannot use the strip_tags() function, because this function can only retain the desired html tags, such as:
strip_tags($string); //去掉$string字符串中所以的html标签. strip_tags($string,'<div><img><em>'); //去掉除了<div><img><em>以外的所有标签,即保留字符串中的div、img、em标签。
To remove the specified For html tags, we can only write a function ourselves. The function is as follows:
function strip_only_tags($str, $tags, $stripContent = FALSE) { $content = ''; if (!is_array($tags)) { $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags)); if (end($tags) == '') { // http://www.manongjc.com/article/1213.html array_pop($tags); } } foreach($tags as $tag) { if ($stripContent) { $content = '(.+<!--'.$tag.'(-->|s[^>]*>)|)'; } $str = preg_replace('#<!--?'.$tag.'(-->|s[^>]*>)'.$content.'#is', '', $str); } return $str; }
Parameter introduction:
$str refers to the string that needs to be filtered.
$tags refers to the html tags to be removed.
$stripContent indicates whether to remove the content in the tag. The default is False, which means the content in the tag will not be deleted.
Usage examples:
<?php $string='<div><a href="http://www.manongjc.com">码农教程<em>斜体</em></a><strong>加粗</strong></div>'; $target = strip_only_tags($string, array('a','em'));//移除$string字符串内的a、em、b标签。 var_dump($target); $target = strip_only_tags($string, array('em'),true); //移除$string字符串内的a、em、b标签,并移除标签里面的内容 var_dump($target); ?>
Summary:
I believe that friends will learn from this article and be familiar with strip_tags( in php ) only filters a certain tag in the string. I have a certain understanding. I hope it will be helpful to your work!
Related recommendations;
Detailed explanation of the shortcomings of the PHP function strip_tags
Detailed introduction of PHP common function strip_tags
php string function strip_tags() usage summary
The above is the detailed content of Example analysis of strip_tags() in php that only filters a certain tag in the string. For more information, please follow other related articles on the PHP Chinese website!