Originally Posted by Custard7A
There are much better ways to preserve preformatted text, I'm sure. A line of nbsp's is a good way to tell you're doing something wrong. I suppose the proper method depends on what's happening with the data before it reaches the page (Passing through a database, etc).
Agreed. Use CSS for your markup; assuming this is coming from some storage or input, you likely have an intent to display it in some relevant element block. Its as simple as forcing a pre whitespace:
$s = 'This had 5 spaces';
printf('<span style="white-space: pre;">%s</span>', $s);
Patterning this one is more of a pain than it looks. It would be trivial to replace multiple whitespace with a single , but more complex to perform many replacements for a single character that is in a multiple sequence. Use the preformat instead as its a lot easier and you needn't worry about the data for the medium that you are using.