Q . How to minify HTML without touching Javascript code Using PHP?

Mike Tyson. asked, Mar 28 ' 2018

I have a web page where I need to minify HTML code without touching JS code.
If I compress JS it stops working. I found so many code in Google but all minify JS code as well.

  • PHP
  • JavaScript
  • HTML
  • minify
  • compress

1 Answers

Here is your solution.

<?php 

function sanitize_output($buffer) {

    //Searching textarea, pre and javascript
    preg_match_all('#<textarea.*?>.*?<\/textarea>#is', $buffer, $foundTxt);
    preg_match_all('#<pre.*?>.*?<\/pre>#is', $buffer, $foundPre);
    preg_match_all('#<script.*?>.*?<\/script>#is', $buffer, $foundScript);
    #preg_match_all('/<textarea([^>]+)?>((?!<\/textarea>).)*<\/textarea>/Uis', $buffer, $foundTxt);
    #preg_match_all('/<pre([^>]+)?>((?!<\/pre>).)*<\/pre>/Uis', $buffer, $foundPre);
    #preg_match_all('/<script([^>]+)?>((?!<\/script>).)*<\/script>/Uis', $buffer, $foundScript);

    $buffer = str_replace($foundTxt[0], array_map(function($el) {
                return '<textarea>' . $el . '</textarea>';
            }, array_keys($foundTxt[0])), $buffer);

    $buffer = str_replace($foundPre[0], array_map(function($el) {
                return '<pre>' . $el . '</pre>';
            }, array_keys($foundPre[0])), $buffer);

    $buffer = str_replace($foundScript[0], array_map(function($el) {
                return '<script>' . $el . '</script>';
            }, array_keys($foundScript[0])), $buffer);

    //your stuff
    $search = array(
        '/\>[^\S ]+/s', //strip whitespaces after tags, except space
        '/[^\S ]+\</s', //strip whitespaces before tags, except space
        '/(\s)+/s'      //shorten multiple whitespace sequences
    );

    $replace = array(
        '>',
        '<',
        '\\1'
    );

    $buffer = preg_replace($search, $replace, $buffer);

    // Replacing back with content
    $buffer = str_replace(array_map(function($el) {
                return '<textarea>' . $el . '</textarea>';
            }, array_keys($foundTxt[0])), $foundTxt[0], $buffer);

    $buffer = str_replace(array_map(function($el) {
                return '<pre>' . $el . '</pre>';
            }, array_keys($foundPre[0])), $foundPre[0], $buffer);

    $buffer = str_replace(array_map(function($el) {
                return '<script>' . $el . '</script>';
            }, array_keys($foundScript[0])), $foundScript[0], $buffer);

    return $buffer;
}

ob_start("sanitize_output");
?>

//Your Code

<?php ob_end_flush(); ?>

 

Leave a Ansewer