最直接方式是用 std::regex_replace 配合正则如 "</?b>" 清除非嵌套、ASCII-only 的简单标签;但因其不支持 Unicode、嵌套及多行结构,且 GCC libstdc++ 有 bug,故不适用于 script/style 等复杂场景,推荐用 pugixml 等解析器安全处理。

用 std::regex_replace 移除指定 HTML 标签(如 <p>、<div>)
最直接的方式是正则替换,但要注意 C++11 的 std::regex 对 Unicode 和嵌套标签完全无感,只适合简单、非嵌套、ASCII-only 的清理场景。比如清除所有 <b> 和 </b>:
std::string html = "<b>hello</b> world <b>again</b>";
std::string clean = std::regex_replace(html, std::regex("</?b>"), "");注意 </?b> 中的 /? 表示可选斜杠,能同时匹配开始和结束标签;但这个正则无法区分 <br> 或 <button>,因为 b 是字面量。
为什么不用 std::regex 清除 <script> 或 <style> 块
这类标签通常跨多行、含属性、内部有嵌套或注释,std::regex 无法安全处理。例如:<script type="text/javascript">var s = "<div>";</script> —— 正则很容易在引号内误匹配 </div>,导致删错位置。更糟的是,GCC 的 libstdc++ 在 C++17 前对 std::regex 的实现有已知 bug,std::regex_search 可能崩溃或漏匹配。Clang 的 libc++ 稍好,但仍不推荐用于生产环境的 HTML 清洗。
使用 PptxGenJS 和 Python 解析,将结构化的 HTML/CSS 幻灯片内容转换为原生、可编辑的 PowerPoint(.pptx)演示文稿。
用 tinyxml2 或 pugixml 安全剥离标签(推荐)
真正健壮的做法是解析成 DOM 树再提取文本,避开正则陷阱。以 pugixml 为例(轻量、头文件即用):
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_string(html.c_str(), pugi::parse_html);
if (result) {
std::string text = doc.document_element().text().get();
// 注意:这仅取根节点直接文本,不含子元素内联文本
}但这样会丢掉所有结构化内容。更常用的是遍历并拼接所有文本节点:std::string strip_tags(const pugi::xml_node& node) {
std::string out;
for (pugi::xml_node child : node.children()) {
out += strip_tags(child);
}
if (node.type() == pugi::node_pcdata || node.type() == pugi::node_cdata) {
out += node.value();
}
return out;
}它能正确跳过 <script>、<style>、注释等节点,且自动处理实体(如 )。
删除特定标签但保留其内容(如去掉 <i> 但留斜体文字)
这需要「替换为子节点内容」而非单纯删除标签。用 pugixml 可递归展开:
void unwrap_tag(pugi::xml_node& node, const char* tag_name) {
for (pugi::xml_node child = node.first_child(); child; ) {
pugi::xml_node next = child.next_sibling();
if (std::strcmp(child.name(), tag_name) == 0) {
// 把当前标签的所有子节点移到父节点中
for (pugi::xml_node grandchild = child.first_child(); grandchild; ) {
pugi::xml_node gnext = grandchild.next_sibling();
node.insert_copy_before(grandchild, child);
grandchild = gnext;
}
child.remove();
}
child = next;
}
}调用 unwrap_tag(doc.document_element(), "i") 后,<i>hello</i> 就变成纯 hello。注意:不能在遍历时直接修改 child 的 parent,所以必须先保存 next。
真正难的不是写几行正则,而是判断哪些标签该删、哪些要留内容、哪些需转义、是否要保留换行或空格。HTML 解析器不是银弹——pugixml 默认按 XML 规则解析,遇到 <br> 这类自闭合标签需启用 pugi::parse_html 模式,否则会报错或截断。别图省事用正则扫一遍就上线。


















