除了标签[重复]之外,使用strip_tags()删除标签属性

除了标签[重复]之外,使用strip_tags()删除标签属性

问题描述:

This question already has an answer here:

I am aware and know how to use strip_tags() with php, but I am wanting to remove all stylings that are contained in those tags.

I need to retain the following tags only

<p></p>
<a></a>
<br />

Not sure br is considered a tag with strip_tags, so I included it.

Example Before:

<p style="font-family: Arial, Verdana, Helvetica, sans-serif; font-size: 13px; padding: 0px; margin: 3px 0px 10px; color: rgb(0, 0, 0); line-height: 16px;">

After:

<p>

Problem is I am not sure if I can accomplish this with strip tags or if I also need to include a preg_replace with some REGEX. Also the styling can vary at times so it needs to be something that can handle anything.

I found an example on php.net but does not seem to work

function strip_tags_content($text, $tags = '', $invert = FALSE) { 

  preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags); 
  $tags = array_unique($tags[1]); 

  if(is_array($tags) AND count($tags) > 0) { 
    if($invert == FALSE) { 
      return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text); 
    } 
    else { 
      return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text); 
    } 
  } 
  elseif($invert == FALSE) { 
    return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text); 
  } 
  return $text; 
}
?>
<?=strip_tags_content($row['notes'])?></p>
</div>

I would do something like:

$x = preg_replace("/<(p|a|b|div) [^>]*>/", "<$1>", $x);

With all your relevant tags in there of course. Note that this will fail in cases where any parameter has a > sign in it so you must cope with quotes somehow.

You can use JQuery instead if you simply want to remove the style from the elements after executing strip_tags($text, '<p><a><br>')

JQuery code

$("container").children().each(function()
    {
        $(this).attr('style','');
    });

Fiddle demo