0

I want to minify HTML code using PHP && Regex code

The minify function :

public static function sanitize_output($buffer) {

    $search = array(
        '/ {2,}/',
        '/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s'
    );
    $replace = array(
        ' ',
        ''
    );
    $buffer = preg_replace($search, $replace, $buffer);

    return $buffer;
}

I use this function when I rendering the template (HTML file), but I get always this error on console

SyntaxError: missing } in compound statement note: { opened at line

The minify code delete some " { " on Js code, is there any solution the fix this problem?

After some search, I found that the error is in JS comments, when I minify the HTML code the comments concatenate with the code.

I try to use this regex

/\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/ 

but it's doesn't work

5
  • 4
    There are pre-made minification solutions for PHP available, why go through the strain of coding one yourself? RegEx for HTML is a bad idea, even for minification it would be a better idea to use a full-fledged parser instead. Commented Apr 6, 2019 at 16:07
  • @Connum what's this method sir ? Commented Apr 6, 2019 at 16:31
  • With some search I found that error caused from the JS comment, is there any regex to delete the JS comment ? Commented Apr 6, 2019 at 18:29
  • Is there any solution ? Commented Apr 6, 2019 at 20:25
  • 1
    You can't use RegEx to parse HTML lest you summon the One who should Not Be Named stackoverflow.com/questions/1732348/… Commented Apr 6, 2019 at 21:28

1 Answer 1

0

Like you say, when you Minify your code using the function, all the HTML code be in single line, for that any code after a JS comments well be a comment to. So You can use this PHP regex to remove inline JavaScript comment :

Your new function :

 public static function sanitize_output($buffer) {

        $search = array(
            '#^\s*//.+$#m', //remove JS comment,
            '/ {2,}/',
            '/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s'
        );
        $replace = array(
            '',
            ' ',
            ''
        );
        $buffer = preg_replace($search, $replace, $buffer);

        return $buffer;
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.