I am guilty of writing that code more than 2 years back :P
That can be hugely simplified by this code:
# remove spaces from start or after / RewriteRule ^(.*/|)[\s%20]+(.+)$ $1$2 [L] # remove spaces from end or before / RewriteRule ^(.+?)[\s%20]+(/.*|)$ $1$2 [L] # replace spaces by - in between RewriteRule ^([^\s%20]*)(?:\s|%20)+(.*)$ $1-$2 [L,R]
PS: Must add that you need to fix the source of these URLs also because it is really not normal to be getting URLs like this.