河汉清且浅,牵牛敦而纯
# HTML是一种 标记语言,主要有元素、标签、属性,一对开闭标签连同里面的内容叫一个元素。
# 元素:<标签 属性名="属性值">内容</标签>

# 删除标签的属性,和 strip_tags($str, '<p><a>') 功能类似,保留内容和指定的标签
function strip_tab_attributes($html){
    $array  = array('<a', '<img', '<video', '<source'); # 要保留其属性的标签
    preg_match_all('/\<[a-zA-Z]+\s/i', $html, $matches); // print_r($matches);

    foreach($matches[0] as $key => $value){
        echo $value ."\n";
        $value = trim($value);
        // if(strtolower($value) === '<a' or strtolower($value) === '<img') continue;
        if (in_array($value, $array)) {
            echo $value ." 标签的属性是被保留的<br>\n";
            continue;
        }
        $html = preg_replace('/'. $value .'\s+[^>]*?>/i', $value.'>', $html);
        # 千问给的答案: 把 <div class="test" id="box"> 变成 <div>
        // $html = preg_replace('/<(\w+)\s[^>]*>/', '<$1>', $html);
    }
    return $html;
}
// $html = strip_tab_attributes($html);
// echo $html ."\n\n"

# 只删除指定的标签
function strip_html_tags($tags, $str) {
    $html = [];
    foreach ($tags as $tag) {
        $html[] = "/(<(?:\/". $tag. "|". $tag. ")[^>]*>)/i";
    }
    return preg_replace($html, '', $str);
}
// echo strip_html_tags(['p', 'img'], $str);


# 删除标签及标签内的内容‌,true 表示删内容,false 表示只删标签
function stripHtmlTags(array $tags, string $str, bool $removeContent = true): string {
    $patterns = [];

    foreach ($tags as $tag) {
        if ($removeContent) {
            // 连标签带内容一起删
            $patterns[] = '/<' . $tag . '[^>]*>[\s\S]*?<\/' . $tag . '>/is';
        } else {
            // 只删标签,保留内容
            $patterns[] = '/<\/?' . $tag . '[^>]*>/is';
        }
    }

    return preg_replace($patterns, '', $str);
}

  

posted on 2026-10-20 13:54  伊索  阅读(7)  评论(0)    收藏  举报