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 1:

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);

Solution 2:

You can try this perhaps.

// Before any output
ob_start();

// End of file
$output = ob_get_clean();
echo preg_replace('/^\s+|\n|\r|\s+$/m', '', $output);

This should, unless I messed up the regex, catch all output, and then replace all new line characters as well as all whitespace at the end and beginning of lines.

If you already have all output collected in a variable, you can of course just use the last line directly and skip the output buffering stuff :)