Remove all the line breaks from the html source

前端 未结 9 2028
情书的邮戳
情书的邮戳 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:09

    This is an improved function of the above. It adds text area protection and also anything that is a tag remains untouched.

    I also removed strlen in the loop (its static).

    This might run faster as a one pass filter to check for any of the protected parts. For such a small protected_parts array it's going to be more efficient than looping through the $str four times.

    Also this doesn't fix: class = " " (the extra spaces between = and ") as its stuff inside the tags.

    function MinifyHTML($str) {
    $protected_parts = array('
    ,
    ','', '<,>'); $extracted_values = array(); $i = 0; foreach ($protected_parts as $part) { $finished = false; $search_offset = $first_offset = 0; $end_offset = 1; $startend = explode(',', $part); if (count($startend) === 1) $startend[1] = $startend[0]; $len0 = strlen($startend[0]); $len1 = strlen($startend[1]); while ($finished === false) { $first_offset = strpos($str, $startend[0], $search_offset); if ($first_offset === false) $finished = true; else { $search_offset = strpos($str, $startend[1], $first_offset + $len0); $extracted_values[$i] = substr($str, $first_offset + $len0, $search_offset - $first_offset - $len0); $str = substr($str, 0, $first_offset + $len0).'$$#'.$i.'$$'.substr($str, $search_offset); $search_offset += $len1 + strlen((string)$i) + 5 - strlen($extracted_values[$i]); ++$i; } } } $str = preg_replace("/\s/", " ", $str); $str = preg_replace("/\s{2,}/", " ", $str); $replace = array('> <'=>'><', ' >'=>'>','< '=>'<',''

提交回复
热议问题