Skip to content

Commit 557ce3f

Browse files
authored
fix: strip embedded markup before text conversion (#6751)
1 parent db50eb1 commit 557ce3f

2 files changed

Lines changed: 27 additions & 8 deletions

File tree

‎apps/common/tests.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from django.test import SimpleTestCase
2+
3+
from common.utils.common import markdown_to_plain_text
4+
5+
6+
class MarkdownToPlainTextTestCase(SimpleTestCase):
7+
def test_removes_embedded_markup_contents(self):
8+
cases = {
9+
'before <audio src="clip.mp3">audio fallback</audio> after': "before after",
10+
'before <video src="clip.mp4">video fallback</video> after': "before after",
11+
'before <form_rander>{"label":"private"}</form_rander> after': "before after",
12+
}
13+
14+
for markup, expected in cases.items():
15+
with self.subTest(markup=markup):
16+
self.assertEqual(markdown_to_plain_text(markup), expected)

‎apps/common/utils/common.py‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -159,8 +159,18 @@ def _remove_empty_lines(text):
159159

160160

161161
def markdown_to_plain_text(md: str) -> str:
162+
# 先移除特定媒体标签(优先级高于通用 Markdown 和 HTML 处理)
163+
text = re.sub(
164+
r"<(audio|video)(?:\s+[^>]*)?>.*?</\1>",
165+
"",
166+
md,
167+
flags=re.DOTALL | re.IGNORECASE,
168+
)
169+
text = re.sub(r"<img[^>]*>", "", text) # 匹配图片标签
170+
# 去除表单渲染
171+
text = re.sub(r"<form_rander>.*?<\/form_rander>", "", text, flags=re.DOTALL)
162172
# 移除图片 ![alt](url)
163-
text = re.sub(r"!\[.*?\]\(.*?\)", "", md)
173+
text = re.sub(r"!\[.*?\]\(.*?\)", "", text)
164174
# 移除链接 [text](url)
165175
text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text)
166176
# 移除 Markdown 标题符号 (#, ##, ###)
@@ -179,15 +189,8 @@ def markdown_to_plain_text(md: str) -> str:
179189
text = re.sub(r"\n{2,}", "\n", text)
180190
# 使用正则表达式去除所有 HTML 标签
181191
text = re.sub(r"<[^>]+>", "", text)
182-
# 先移除特定媒体标签(优先级高于通用HTML标签移除)
183-
text = re.sub(
184-
r"<(?:audio|video)(?:\s+[^>]*)?>.*?(?:</(?:audio|video)>)?", "", text, flags=re.DOTALL | re.IGNORECASE
185-
)
186-
text = re.sub(r"<img[^>]*>", "", text) # 匹配图片标签
187192
# 去除多余的空白字符(包括换行符、制表符等)
188193
text = re.sub(r"\s+", " ", text)
189-
# 去除表单渲染
190-
text = re.sub(r"<form_rander>.*?<\/form_rander>", "", text, flags=re.DOTALL)
191194
# 去除首尾空格
192195
text = text.strip()
193196
return text

0 commit comments

Comments
 (0)