如何配置HTML Purifier以允许URL中的下划线?
解决HTML Purifier过滤含下划线URL的问题
问题背景
当插入包含下划线的URL链接(如:
<p><code>For more information <a href="https://example.com/sample_doc.html">read the docs</a>.</code></p>
)时,HTML Purifier会过滤掉<a>标签href属性中的完整URL,仅保留标签文本内容,输出结果为:
<p><code>For more information <a>read the docs</a>.</code></p>
当前使用的配置如下:
{ "Attr.AllowedFrameTargets": [ "_blank" ], "Attr.EnableID": true, "HTML.AllowedComments": [ "pagebreak" ], "HTML.SafeIframe": true, "URI.SafeIframeRegexp": "%^(https?:)?//(www.youtube.com/|player.vimeo.com/)%" }
解决方案
要让HTML Purifier允许URL中包含下划线,需在配置中添加以下关键设置:
- 显式指定允许的URL字符:通过
URI.AllowedCharacters明确包含下划线,同时覆盖所有合法URL字符,避免环境差异导致的过滤。 - 确保
a标签的href属性被允许:若环境默认属性列表被修改,需通过HTML.AllowedAttributes明确添加a.href。
修改后的完整配置:
{ "Attr.AllowedFrameTargets": [ "_blank" ], "Attr.EnableID": true, "HTML.AllowedComments": [ "pagebreak" ], "HTML.SafeIframe": true, "URI.SafeIframeRegexp": "%^(https?:)?//(www.youtube.com/|player.vimeo.com/)%", "URI.AllowedCharacters": "a-zA-Z0-9\\-._~:/?#[]@!$&'()*+,;=", "HTML.AllowedAttributes": "a.href", "URI.AllowedSchemes": { "http": true, "https": true, "mailto": true } }
配置说明
URI.AllowedCharacters中的_确保下划线可出现在URL的路径、文件名等位置。URI.AllowedSchemes明确允许http、https和mailto协议,避免外部URL被误过滤。HTML.AllowedAttributes确保<a>标签的href属性不会被过滤。
内容的提问来源于stack exchange,提问作者J1989
相关产品推荐
相关产品推荐

