替换掉html中多余的html标签和属性

2019-12-12 16:05  2909人阅读  评论 (0)
Tags: php

替换掉html中多余的html标签和属性

版本1

function strip_html($html) {
    // 替换正文中的div标签为p标签 替换非空格的空白字符为空格
    $html = str_replace(['<div', 'div>', '<section', 'section>', ' ', ' ', '\xc2', '\xa0'], ['<p', 'p>', '<p', 'p>', ' ', ' ', ' ', ' '], $html);
    //保留 p、b标签
    $html = strip_tags($html, '<p><b><strong><em><br>');
    //过滤 html标签的属性
    $html = preg_replace('/<(\w+)[^>]*>/is','<\1>', $html);
    // 找到所有包含内容的p段落
    preg_match_all('/<p>(?:.(?!<p>))*?<\/p>/is', $html, $matches);
    // var_dump($matches);
    // 将匹配到的数组拼接成字符串
    $html = implode("\n", $matches[0]);
    // 递归删除空段落
    $html = preg_replace('/(?:<(\w+)>\s*(?R)\s*<\/\1>)*/i', '', $html);
    // 删除段落开始的空白
    $html = preg_replace('/<(\w+)>\s*/is', '<\1>', $html);
    // 删除段落结尾的空白
    $html = preg_replace('/\s*<\/(\w+)>/is', '</\1>', $html);
    // 删除多余的换行
    return preg_replace('/\n{2,}/is', "\n", $html);
}

版本2

function strip_body($body) {
  // 替换非空格的空白字符为空格
  $body = str_replace(['&nbsp;', ' ', '\xc2', '\xa0'], [' ', ' ', ' ', ' '], $body);
  // 删除所有 html 标签的属性
  $body = preg_replace('/<(\w+)[^>]*>/is','<\1>', $body);
  // 将 section div p br 替换为 p 标签
  $body = preg_replace('/(<\/?section>|<\/?div>|<\/?p>|<br[^>]*>)/is', "\n", $body);
  // 删除其他 html 标签
  $body = strip_tags($body, '<b><strong><em>');
  // 删除行首 行尾的空白字符
  $body = preg_replace('/^\s*|\s*%/', '', $body);
  // 将多余的换行删除
  $body = preg_replace('/\n{2,}/s', "\n", $body);
  // 加上 p 标签
  $body = preg_replace('/\n/is', "</p>\n</p>", $body);
  return "<p>$body</p>";
}
豫ICP备09035262号-1