Skip to content

Instantly share code, notes, and snippets.

@rafasashi
Last active November 28, 2019 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafasashi/59c9448f5467ea427fa3 to your computer and use it in GitHub Desktop.
Save rafasashi/59c9448f5467ea427fa3 to your computer and use it in GitHub Desktop.
strip a single html tag
function strip_single_tag($str,$tag=''){
if(is_array($tag)){
foreach($tag as $t){
$str=strip_single_tag($str,$t);
}
}
else{
$str1=preg_replace('/<\/'.$tag.'>/i', '', $str);
if($str1 != $str){
$str=preg_replace('/<'.$tag.'[^>]*>/i', '', $str1);
}
}
return $str;
}
@wolfkang
Copy link

Hi,
strip_single_tag('<pre>abc</pre>','p') returns 'abc</pre>'.

@rafasashi
Copy link
Author

Thanks wolfkang ! What about now?

@meagar
Copy link

meagar commented Nov 28, 2019

This is incorrect and dangerous. You cannot strip tags from HTML using regular expressions. Consider how your code will handle stripping div tags from this input:

<!doctype html>
<html lang="en">
  <head><title>foo</title></head>
  <body>
  <div>
    <script>
      let x = "</div>"
    </script>
  </div>
</body>
</html>

You need a DOM parser for working with HTML documents.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment