Geoff Garbers

Husband. Programmer. Tinkerer.

Using a non-breaking space in UTF-8 documents

Sep 22, 2011

I’m pedantic when it comes to displaying nested items in a dropdown. I like to ensure that sub-items are suitably indented. My preference is to do this using spaces only. However, the problem in HTML is that multiple spaces are considered as one. Which blows this out of the water.

Why not just use a non-breaking space character? Duh!

You mean something like the output of PHP’s chr(160)? That was my first thought. However - this character is not part of the UTF-8 character set (my default character set); and is actually a part of the ISO-8859-1 character set.

Thankfully, I stumbled across a great snippet that outputs a UTF-8 suitable non-breaking space:

echo mb_convert_encoding(chr(160), 'UTF-8', 'HTML-ENTITIES');

I know it is possible to insert a   into the HTML. However, this was for use in a CakePHP project - where the form items are automagically generated, and using the   in multiple places became a bit tricky.