Stripping HTML comments from a string in PHP

Bellow is a PHP function for stripping HTML comments out of a string. It is useful when working with raw data, caching engines or data, extracted from another website.

function strip_comments($data) {
    $the_rest = $data;
    $result = "";

    while ($the_rest) {
        $start = strpos($the_rest, "<!--");
        if ($start === false) {
            $result .= $the_rest;
            break;
        }

        $result .= substr($the_rest, 0, $start);

        $end = strpos($the_rest, "-->", $start);
        if ($end === false) {
            break;
        }

        $the_rest = substr($the_rest, $end+3);
    }

    return $result;
}

 

 

No comments yet

Back to articles list

This page was last modified on 2018-12-09 01:29:50