Strip HTML tags other than provided tags and attributes.
    Example usage:

    {% load sanitizer %}
    {{ post.body|sanitize_allow:'a, strong, img; href, src'}}
514385
def sanitize_allow(value, args=''):
    '''
    
    '''
    if isinstance(value, basestring):
        allowed_tags = []
        allowed_attributes = []
        allowed_styles = []
        
        args = args.strip().split(';')
        if len(args) > 0:
            allowed_tags = [tag.strip() for tag in args[0].split(',')]
        if len(args) > 1:
            allowed_attributes = [attr.strip() for attr in args[1].split(',')]
            
        value = bleach.clean(value, tags=allowed_tags,
                             attributes=allowed_attributes, strip=True)
    return value
239036
def clean_html(context, data):
    """"""
    doc = _get_html_document(context, data)
    if doc is None:
        context.emit(data=data)
        return

    remove_paths = context.params.get('remove_paths')
    for path in ensure_list(remove_paths):
        for el in doc.findall(path):
            el.drop_tree()

    html_text = html.tostring(doc, pretty_print=True)
    content_hash = context.store_data(html_text)
    data['content_hash'] = content_hash
    context.emit(data=data)
2158
protected static function sanitizeNaughtyHTML($matches)
    {
        // First, escape unclosed tags
        if (empty($matches[ 'closeTag' ])) {
            return '&lt;' . $matches[ 1 ];
        } // Is the element that we caught naughty? If so, escape it
        elseif (in_array(strtolower($matches[ 'tagName' ]), self::getConfig('naughty_tags'), true)) {
            return '&lt;' . $matches[ 1 ] . '&gt;';
        } // For other tags, see if their attributes are "evil" and strip those
        elseif (isset($matches[ 'attributes' ])) {
            // We'll store the already fitlered attributes here
            $attributes = [];

            // Attribute-catching pattern
            $attributesPattern = '#'
                . '(?<name>[^\s\042\047>/=]+)'
                // attribute characters
                // optional attribute-value
                . '(?:\s*=(?<value>[^\s\042\047=><`]+|\s*\042[^\042]*\042|\s*\047[^\047]*\047|\s*(?U:[^\s\042\047=><`]*)))'
                // attribute-value separator
                . '#i';

            // Blacklist pattern for evil attribute names
            $is_evil_pattern = '#^(' . implode('|', self::getConfig('evil_attributes')) . ')$#i';

            // Each iteration filters a single attribute
            do {
                // Strip any non-alpha characters that may preceed an attribute.
                // Browsers often parse these incorrectly and that has been a
                // of numerous XSS issues we've had.
                $matches[ 'attributes' ] = preg_replace('#^[^a-z]+#i', '', $matches[ 'attributes' ]);

                if ( ! preg_match($attributesPattern, $matches[ 'attributes' ], $attribute, PREG_OFFSET_CAPTURE)) {
                    // No (valid) attribute found? Discard everything else inside the tag
                    break;
                }

                if (
                    // Is it indeed an "evil" attribute?
                    preg_match($is_evil_pattern, $attribute[ 'name' ][ 0 ])
                    // Or does it have an equals sign, but no value and not quoted? Strip that too!
                    OR (trim($attribute[ 'value' ][ 0 ]) === '')
                ) {
                    $attributes[] = 'xss=removed';
                } else {
                    $attributes[] = $attribute[ 0 ][ 0 ];
                }

                $matches[ 'attributes' ] = substr(
                    $matches[ 'attributes' ],
                    $attribute[ 0 ][ 1 ] + strlen($attribute[ 0 ][ 0 ])
                );
            } while ($matches[ 'attributes' ] !== '');
            $attributes = empty($attributes)
                ? ''
                : ' ' . implode(' ', $attributes);

            return '<' . $matches[ 'slash' ] . $matches[ 'tagName' ] . $attributes . '>';
        }

        return $matches[ 0 ];
    }
1103752
function htmlSanitizer(html, needHtmlText) {
  const $html = $('<div />');

  html = html.replace(/<!--[\s\S]*?-->/g, '');

  $html.append(html);

  removeUnnecessaryTags($html);
  leaveOnlyWhitelistAttribute($html);

  return finalizeHtml($html, needHtmlText);
}
985779
def striptags(self):
        
        """
        stripped = u' '.join(_striptags_re.sub('', self).split())
        return Markup(stripped).unescape()
1301371
function filterAttribute(html, config) {
    var result = html;
    var tempHTML = html;

    (function() {
        //
        var attrMatches = REGEXP_ATTR_WITH_TAG.exec(tempHTML);
        REGEXP_ATTR_WITH_TAG.lastIndex = 0;

        if (attrMatches) {
            var labelHasAttr = attrMatches[1];
            var attrArray = labelHasAttr.match(REGEXP_ATTR);

            tempHTML = tempHTML.replace(labelHasAttr, '');

            utils.each(attrArray, function(item) {
                var attrName = utils.str_trim(item.substr(0, item.indexOf('='))).toLowerCase();

                if (config.blackListAttrs[attrName]) {
                    result = result.replace(item, '');
                }
            });

            arguments.callee();
        }
    })();

    return result;
}
452709
def sanitize_config
      {
        elements: %w(
          p br a span sub sup strong em div hr abbr s
          ul ol li
          blockquote cite pre code kbd
          h1 h2 h3 h4 h5 h6
          img object param del
          table tr td th thead tbody
          figure figcaption
          mark del ins
        ),
        attributes: {
          :all     => ['class', 'style', 'title', 'id', 'datetime'],
          'a'      => ['href', 'rel', 'name'],
          'li'     => ['id'],
          'sup'    => ['id'],
          'img'    => ['src', 'title', 'alt', 'width', 'height'],
          'object' => ['width', 'height'],
          'param'  => ['name', 'value'],
          'embed'  => ['allowscriptaccess', 'width', 'height', 'src'],
          'iframe' => ['width', 'height', 'src'],
          'td'     => ['colspan', 'rowspan'],
          'th'     => ['colspan', 'rowspan']
        },
        protocols: {
          'a' => { 'href' => ['ftp', 'http', 'https', 'mailto', '#fn', '#fnref', :relative] },
          'img' => {'src'  => ['http', 'https', :relative]},
          'iframe' => {'src'  => ['http', 'https']},
          'embed' => {'src'  => ['http', 'https']},
          'object' => {'src'  => ['http', 'https']},
          'li' => {'id' => ['fn']},
          'sup' => {'id' => ['fnref']}
        },
        transformers: transformers
      }
    end
174627
def _remove_pre_formatting(self):
        
        preformatted_wrappers = [
            'pre',
            'code'
        ]

        for wrapper in preformatted_wrappers:
            for formatter in FORMATTERS:
                tag = FORMATTERS[formatter]
                character = formatter

                regex = r'(<{w}>.*)<{t}>(.*)</{t}>(.*</{w}>)'.format(
                    t=tag,
                    w=wrapper
                )
                repl = r'\g<1>{c}\g<2>{c}\g<3>'.format(c=character)
                self.cleaned_html = re.sub(regex, repl, self.cleaned_html)
393804
def handle_starttag(self, tag, attrs):
        
        self.log.debug( u'Encountered a start tag: {0} {1}'.format(tag, attrs) )
        if tag in self.sanitizelist:
            self.level += 1
            return
        if self.isNotPurify or tag in self.whitelist_keys:
            attrs = self.__attrs_str(tag, attrs)
            attrs = ' ' + attrs if attrs else ''
            tmpl = u'<%s%s />' if tag in self.unclosedTags and self.isStrictHtml else u'<%s%s>'
            self.data.append( tmpl % (tag, attrs,) )
739137
def stripIEConditionals(contents, addHtmlIfMissing=True):
    '''
        
    '''
    allMatches = IE_CONDITIONAL_PATTERN.findall(contents)
    if not allMatches:
        return contents

    for match in allMatches:
        contents = contents.replace(match, '')

    if END_HTML.match(contents) and not START_HTML.match(contents):
        contents = addStartTag(contents, '<html>')

    return contents
692464
def strip_bad_html(self):
        
        out = self.string
        while not String(out).is_well_formatted():
            out = out.replace(":", "") \
                .replace("\\'", "\'") \
                .replace("\\n", "") \
                .replace("\\r", "") \
                .replace("\\t", "") \
                .replace("\n", "") \
                .replace("\r", "") \
                .replace("\t", "") \
                .replace("  ", " ") \
                .strip()

        return str(out)
574185
def clean_ns(tag):
    """"""
    if '}' in tag:
        split = tag.split('}')
        return split[0].strip('{'), split[-1]
    return '', tag
646295
def strip_tags(string)
      if defined?(Loofah)
        # Instead of strip_tags we will use Loofah to strip tags from now on
        Loofah.fragment(string).text(encode_special_chars: false)
      else
        helpers.strip_tags(string)
      end
    end
964992
function sanitizeHtml(unsafeHtmlInput) {
	        try {
	            var containerEl = getInertElement();
	            // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).
	            var unsafeHtml = unsafeHtmlInput ? String(unsafeHtmlInput) : '';
	            // mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser
	            // trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous.
	            var mXSSAttempts = 5;
	            var parsedHtml = unsafeHtml;
	            do {
	                if (mXSSAttempts === 0) {
	                    throw new Error('Failed to sanitize html because the input is unstable');
	                }
	                mXSSAttempts--;
	                unsafeHtml = parsedHtml;
	                DOM.setInnerHTML(containerEl, unsafeHtml);
	                if (DOM.defaultDoc().documentMode) {
	                    // strip custom-namespaced attributes on IE<=11
	                    stripCustomNsAttrs(containerEl);
	                }
	                parsedHtml = DOM.getInnerHTML(containerEl);
	            } while (unsafeHtml !== parsedHtml);
	            var sanitizer = new SanitizingHtmlSerializer();
	            var safeHtml = sanitizer.sanitizeChildren(DOM.getTemplateContent(containerEl) || containerEl);
	            // Clear out the body element.
	            var parent_1 = DOM.getTemplateContent(containerEl) || containerEl;
	            for (var _i = 0, _a = DOM.childNodesAsList(parent_1); _i < _a.length; _i++) {
	                var child = _a[_i];
	                DOM.removeChild(parent_1, child);
	            }
	            if (_angular_core.isDevMode() && sanitizer.sanitizedSomething) {
	                DOM.log('WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).');
	            }
	            return safeHtml;
	        }
	        catch (e) {
	            // In case anything goes wrong, clear out inertElement to reset the entire DOM structure.
	            inertElement = null;
	            throw e;
	        }
	    }
1279932
def strip_tags(s):
    """"""

    def handle_match(m):
        name = m.group(1)
        if name in html_entities:
            return unichr(html_entities[name])
        if name[:2] in ("#x", "#X"):
            try:
                return unichr(int(name[2:], 16))
            except ValueError:
                return u""
        elif name.startswith("#"):
            try:
                return unichr(int(name[1:]))
            except ValueError:
                return u""
        return u""

    return _entity_re.sub(handle_match, _striptags_re.sub("", s))
239750
def strip_tags(html):
    
    from html.parser import HTMLParser
    class MLStripper(HTMLParser):
        """Aux class for stripping HTML tags.

         fields on several Mambu entities come with additional HTML tags
        (they are rich text fields, I guess that's why). Sometimes they are
        useless, so stripping them is a good idea.
        """
        def __init__(self):
            try:
                super().__init__() # required for python3
            except TypeError as e:
                pass # with python2 raises TypeError
            self.reset()
            self.fed = []
        def handle_data(self, d):
            self.fed.append(d)
        def get_data(self):
            return ''.join(self.fed)

    s = MLStripper()
    s.feed(html.replace("&nbsp;"," "))
    return s.get_data()
1181870
public String stripHtmlTags(String string)
    {
        for (int i = 1; i < string.length(); i++)
        {
            if (string.charAt(i) == '<')
            {
                int iEndTag = string.indexOf('>', i);
                if (iEndTag != -1)
                {
                    string = string.substring(0, i) + JAVA_NEW_LINE + string.substring(iEndTag + 1);
                    i--;
                }
            }
        }
        return string;
    }