Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

crunch up your HTML into a single line

a handy little script...

8:29 pm on Jun 7, 2007 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month

joined:Feb 12, 2006
votes: 116

this won't be everyone's cup of tea, but i found it pretty handy when someone gave it to me so i thought i'd pass it on.

it's a little script to remove all the line breaks, spaces and gaps between tags. if you stick it around your HTML page then you can write your code with as many spaces and gaps as you want to keep it easy to read, but when it's delivered to the user it will appear as one big line. maybe save a bit of bandwidth.

(it doesn't crunch up anything inside <script> </script> though, because that will frequently break the script)


function stripwhitespace($bff){$pzcr=0;$pzed=strlen($bff)-1;$rst="";while($pzcr<$pzed){
$temp=substr($bff,$t_poz_start,$t_poz_end-$t_poz_start);$rst.=$temp;$pzcr=$t_poz_end;}}return $rst;}
function stripBuffer($bff){$bff=str_replace(array("\r\r\r","\r\r","\r\n","\n\r","\n\n\n","\n\n"),"\n",$bff);
$bff=ereg_replace(" {2,}",' ',$bff);$bff=str_replace("> <","><",$bff);$bff=str_replace(" &nbsp;","&nbsp;",$bff);
$bff=str_replace("&nbsp; ","&nbsp;",$bff);return $bff;}ob_start("stripwhitespace");

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<title>Title of your page</title>


<h1>Name of the page</h1>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean porttitor. Curabitur eros ante, varius sit amet, laoreet at, vehicula dictum, ligula. Cras sed lorem. Aenean dignissim rutrum massa. Aliquam tortor. Vivamus condimentum. Nam mollis ligula sed nisi. Phasellus posuere orci et elit. Nam dapibus bibendum nibh. Curabitur at arcu. Integer pretium. In lobortis feugiat est.</p>

<p>Donec sed est at dolor rhoncus ornare. Nam pellentesque tortor sed diam. Quisque nec odio. Morbi nibh. Sed risus nisi, tincidunt eget, consectetuer id, imperdiet porta, purus. Donec molestie, felis a mollis volutpat, pede lectus semper diam, sed pretium purus tellus nec risus. Proin sagittis ante quis sem. Cras semper magna mollis arcu.</p>


9:25 pm on June 7, 2007 (gmt 0)

Senior Member

joined:Nov 12, 2005
votes: 0

Thanks for the script, londrum.

For those interested this uses the output control functions [php.net]. These are very handy and sometimes necessary, especially when dealing with echoing strings within a loop.

Also, there is a function called php_strip_whitespace [php.net]. I'm sure you can figure out what it does ;)