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

ThaTest
  • 105
  • 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. – Constantin Groß Apr 06 '19 at 16:07
  • @Connum what's this method sir ? – ThaTest Apr 06 '19 at 16:31
  • With some search I found that error caused from the JS comment, is there any regex to delete the JS comment ? – ThaTest Apr 06 '19 at 18:29
  • Is there any solution ? – ThaTest Apr 06 '19 at 20:25
  • 1
    You can't use RegEx to parse HTML lest you summon the One who should Not Be Named https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – ChrisM Apr 06 '19 at 21:28

1 Answers1

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;
    }
sayou
  • 893
  • 8
  • 29