Q:

Add space before question mark and exclamation mark

My client wants to have a space before exclamation marks and question marks. To ensure this always is done correctly I use the following script in php. This script removes any existing spaces and then puts a non-breaking space before all question marks and exclamation marks:
$text =  str_replace(' ?', '?', $text);
$text = str_replace('?', '&nbsp;?', $text);
$text = str_replace(' !', '!', $text);
$text = str_replace('!', '&nbsp;!', $text);
return $text;

This all works fine but I was wondering if there's a better way with Regex?

A:

You may use
$text = "No? Oh ? And ! and!";
$text = preg_replace('~\s*([?!])~',  '&nbsp;$1', $text);
echo $text;

See the PHP demo
Details:

\s* - 0+ whitespace symbols
([?!]) - Group 1 capturing ? or !

The replacement pattern only contains &nbsp; and the backreference to Group 1 contents to insert the captured text.

A:

Use preg_replace
With regex it would look like this: 
preg_replace('/(\S)([?!])/', '$1 $2', $text);

