Remove all the line breaks from the html source

前端 未结 9 1981
情书的邮戳
情书的邮戳 2020-11-27 04:50

Well I know obfuscation is a bad idea. But I want all of my html code to come in one long single line. All the html tags are generated through PHP, so I think its possible.

相关标签:
9条回答
  • 2020-11-27 05:26

    Worked for me:

    $output = str_replace(array("\r\n", "\r", "\n"), "", $output);
    
    0 讨论(0)
  • 2020-11-27 05:26

    You can't have <div> inside <p> - it is not spec-valid.

    If you don't need to store it in a variable you can use this:

    ?><div><?php
        ?><div class="title">Hello</div><?php
    ?></div><?php
    
    0 讨论(0)
  • 2020-11-27 05:29

    This is a (as far as I have tested) working implementation of Stephen Chung's instructions. I'm not entirely convinced by number five, but have included it anyway.

    Put the things you want to protect in the protected_parts array. Do it in order that you want them protected. If the starting and ending bits are different (as they would be in HTML tags), separate them by using a comma.

    Also, I've no idea if this is the most optimised way of doing this, but it works for me and seems reasonably fast. Feel free to improve, etc. (Let me know if you do too!)

    function MinifyHTML($str) {
        $protected_parts = array("<pre>,</pre>", "\"", "'");
        $extracted_values = array();
        $i = 0;
    
        foreach ($protected_parts as $part) {
            $finished = false;
            $search_offset = 0;
            $first_offset = 0;
            $startend = explode(",", $part);
            if (count($startend) == 1) { $startend[1] = $startend[0]; }
    
            while (!$finished) {
                $first_offset = strpos($str, $startend[0], $search_offset);
                if ($first_offset === false) { $finished = true; }
                else {
                    $search_offset = strpos($str, $startend[1], $first_offset + strlen($startend[0]));
                    $extracted_values[$i] = substr($str, $first_offset + strlen($startend[0]), $search_offset - $first_offset - strlen($startend[0]));
                    $str = substr($str, 0, $first_offset + strlen($startend[0]))."$#".$i."$".substr($str, $search_offset);
                    $search_offset += strlen($startend[1]) + strlen((string)$i) + 3 - strlen($extracted_values[$i]);
                    $i++;
                }
            }
        }
    
        $str = preg_replace("/\s/", " ", $str);
        $str = preg_replace("/\s{2,}/", " ", $str);
        $str = str_replace("> <", "><", $str);
        $str = str_replace(" >", ">", $str);
        $str = str_replace("< ", "<", $str);
        $str = str_replace("</ ", "</", $str);
    
        for ($i = count($extracted_values); $i >= 0; $i--) {
            $str = str_replace("$#".$i."$", $extracted_values[$i], $str);
        }
    
        return $str;
    }
    
    0 讨论(0)
提交回复
热议问题