Remove all the line breaks from the html source

mrN picture mrN · Mar 10, 2011 · Viewed 95.6k times · 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>

Answer

seriousdev picture seriousdev · Mar 10, 2011

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