Search code examples
phphtmlobfuscationwhitespaceline-breaks

Remove all the line breaks from the html source


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. I knew replacing \n\r from regular expression, but have no idea how to do this one. In case I am unclear here is an example

$output = '<p>
              <div class="title">Hello</div>
           </p>';
echo $output;

To be view in the source viewer as <p><div class="title">Hello</div></p>


Solution

  • Maybe this?

    $output = str_replace(array("\r\n", "\r"), "\n", $output);
    $lines = explode("\n", $output);
    $new_lines = array();
    
    foreach ($lines as $i => $line) {
        if(!empty($line))
            $new_lines[] = trim($line);
    }
    echo implode($new_lines);