module.exports = function strip_tags(input, allowed) {
// discuss at: https://locutus.io/php/strip_tags/
// original by: Kevin van Zonneveld (https://kvz.io)
// improved by: Luke Godfrey
// improved by: Kevin van Zonneveld (https://kvz.io)
// input by: Pul
// input by: Alex
// input by: Marc Palau
// input by: Brett Zamir (https://brett-zamir.me)
// input by: Bobby Drake
// input by: Evertjan Garretsen
// bugfixed by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// bugfixed by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Eric Nagel
// bugfixed by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Tomasz Wesolowski
// bugfixed by: Tymon Sturgeon (https://scryptonite.com)
// bugfixed by: Tim de Koning (https://www.kingsquare.nl)
// revised by: RafaĆ Kukawski (https://blog.kukawski.pl)
// example 1: strip_tags('
Kevin
van Zonneveld', '')
// returns 1: 'Kevin van Zonneveld'
// example 2: strip_tags('Kevin van Zonneveld
', '')
// returns 2: '
Kevin van Zonneveld
'
// example 3: strip_tags("Kevin van Zonneveld", "")
// returns 3: "Kevin van Zonneveld"
// example 4: strip_tags('1 < 5 5 > 1')
// returns 4: '1 < 5 5 > 1'
// example 5: strip_tags('1
1')
// returns 5: '1 1'
// example 6: strip_tags('1
1', '
')
// returns 6: '1
1'
// example 7: strip_tags('1
1', '
')
// returns 7: '1
1'
// example 8: strip_tags('hello <script>world</script>')
// returns 8: 'hello world'
// example 9: strip_tags(4)
// returns 9: '4'
const _phpCastString = require('../_helpers/_phpCastString')
// making sure the allowed arg is a string containing only tags in lowercase ()
allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('')
const tags = /<\/?([a-z0-9]*)\b[^>]*>?/gi
const commentsAndPhpTags = /|<\?(?:php)?[\s\S]*?\?>/gi
let after = _phpCastString(input)
// removes tha '<' char at the end of the string to replicate PHP's behaviour
after = after.substring(after.length - 1) === '<' ? after.substring(0, after.length - 1) : after
// recursively remove tags to ensure that the returned string doesn't contain forbidden tags after previous passes (e.g. '<switch/>')
while (true) {
const before = after
after = before.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''
})
// return once no more tags are removed
if (before === after) {
return after
}
}
}