python strip_python strip_tags实现

本文介绍了一个用Python实现的类似于PHP的strip_tags函数,用于从字符串中移除指定的XML风格标签,适用于需要清理HTML内容的场景。通过示例展示了如何使用该函数,并提供了参数允许保留特定标签的选项。
摘要由CSDN通过智能技术生成

Sometimes it is necessary to remove all (or some subset of) xml style tags (eg.

) from a string. If you're familiar with PHP, then you probably already know about the strip_tags() function. Here is a simple equivalent to strip_tags() written in Python.## Remove xml style tags from an input string.

#

# @param string The input string.

# @param allowed_tags A string to specify tags which should not be removed.

def strip_tags(string, allowed_tags=''):

if allowed_tags != '':

# Get a list of all allowed tag names.

allowed_tags_list = re.sub(r'[\/<> ]+', '', allowed_tags).split(',')

allowed_pattern = ''

for s in allowed_tags_list:

if s == '':

continue;

# Add all possible patterns for this tag to the regex.

if allowed_pattern != '':

allowed_pattern += '|'

allowed_pattern += '<' + s + ' [^><]*>$|<' + s + '>|'

# Get all tags included in the string.

all_tags = re.findall(r'<]+>', string, re.I)

for tag in all_tags:

# If not allowed, replace it.

if not re.match(allowed_pattern, tag, re.I):

string = string.replace(tag, '')

else:

# If no allowed tags, remove all.

string = re.sub(r'<[^>]*?>', '', string)

return string

Sample output>>> strip_tags('Hello World!


')

'Hello World! '

>>> strip_tags('Hello World!


', ' ')

'Hello World!'

>>> strip_tags('Hello World!


', ' ,')

'Hello World!


'

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值