3
\$\begingroup\$

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?

\$\endgroup\$
  • \$\begingroup\$ How about <blockquote> tag? \$\endgroup\$ – andrew Jul 11 '14 at 13:42
  • \$\begingroup\$ @andrew doesn't seem to have significant whitespace by default \$\endgroup\$ – Niet the Dark Absol Jul 11 '14 at 13:44
  • \$\begingroup\$ i see. Ok then. \$\endgroup\$ – andrew Jul 11 '14 at 14:05
  • \$\begingroup\$ I'd still use gzip compression, but this regexp looks interesting. \$\endgroup\$ – shudder Jul 11 '14 at 18:02
  • \$\begingroup\$ 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> \$\endgroup\$ – Travis Weston Jul 17 '14 at 20:37
3
\$\begingroup\$
  • 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.
  • There's a big assumption here that the HTML will be well-formed. I assume (ha!) that this is okay.
  • Whitespace is significant in <input> tags.
\$\endgroup\$
  • 1
    \$\begingroup\$ Ooh, that last point... You're right, and especially the value attribute. Should be simple enough to add, in theory. Thanks for the feedback! \$\endgroup\$ – Niet the Dark Absol Aug 5 '14 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.