# Automatic condensing of whitespace in HTML

One of the things that has occurred to me more recently is that if you add up all of the bandwidth that is taken up by thousands of users downloading the newlines and tabs used to make HTML source code readable... that's a LOT of wasted bandwidth.

So I wanted to add some code that would condense whitespace on-the-fly before sending it to the browser.

I then very quickly realised that sometimes, whitespace is significant. For example, in <textarea>s or <pre> tags.

After double-checking, I've come to the firm conclusion that there is absolutely no use of white-space CSS values such as pre-wrap that would make whitespace significant, except in the case of a custom <rainbow> tag (which is parsed by JavaScript for colour codes and things - long story XD)

So with that in mind, I wanted to condense whitespace that is not contained in a <textarea>, <pre> or <rainbow>. I accomplished this with DOMDocument and a DOMXPath, in other words, "doing it right". But then I learned about regex verbs, and replaced my code with this:

// uber hax with regex
$str = trim(preg_replace("(<(textarea|rainbow|pre).*?</\\1>(*SKIP)(*F)|\s+)s"," ",$str));


It, um... well, it works, or at least it seems to from what I can tell. But I wanted to post here so I can ask, have I missed anything important? Or is it really this simple?

• How about <blockquote> tag? Jul 11, 2014 at 13:42
• Jul 11, 2014 at 13:44
• i see. Ok then. Jul 11, 2014 at 14:05
• I'd still use gzip compression, but this regexp looks interesting. Jul 11, 2014 at 18:02
• The only thing I can see that could be improved at the moment is making it case insensitive, currently it doesn't match <TEXTAREA></TEXTAREA> Jul 17, 2014 at 20:37

• I don't see much reason to use (*F) instead of the somewhat more understandable (*FAIL).
• Consider using single-quoted (') strings for regular expressions to avoid \\1.
• Whitespace is significant in <input> tags.
• Ooh, that last point... You're right, and especially the value attribute. Should be simple enough to add, in theory. Thanks for the feedback! Aug 5, 2014 at 18:34