php删除重复的html正文和标题

时间:2011-03-16 02:28:48

标签: php tags strip-tags

我有一个字符串,它被回显到当前文档中,但是,我想只插入<body>内的内容,如何删除这些标记,以便最终得到一个有效的文档。< / p>

$string = '
    <html>
    <head>
    <title>Title</title>
    </head>
    <body>
        <!-- leave any tag within the body -->
    </body>
    </html>
';

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Title</title>
</head>
<body>
    <?php echo $string; // new valid content  ?>
    <!-- more content -->
</body>
</html>

2 个答案:

答案 0 :(得分:0)

您可以搜索<body>标记并添加6以查找起点,然后搜索</body>以查找结束点,然后对字符串执行substr。您需要确保标记中没有任何属性。如果您想确保正确完成此操作,请找到<body,然后找到下一个>并为起点添加1。

答案 1 :(得分:0)

来自php.net;

<?php
function strip_selected_tags($str, $tags = array(), $stripContent = false)
{
    preg_match_all("/<([^>]+)>/i", $tags, $allTags, PREG_PATTERN_ORDER);
    foreach ($allTags[1] as $tag) {
        $replace = "%(<$tag.*?>)(.*?)(<\/$tag.*?>)%is";
        $replace2 = "%(<$tag.*?>)%is";
        echo $replace;
        if ($stripContent) {
            $str = preg_replace($replace,'',$str);
            $str = preg_replace($replace2,'',$str);
        }
            $str = preg_replace($replace,'${2}',$str);
            $str = preg_replace($replace2,'${2}',$str);
    }
    return $str;
}
?>
相关问题