<?php

$s = "This is     my text.";
echo preg_replace('~(?<=\s)\s~', '&nbsp;', $s);
