As per our check, the script works just fine. Make sure it is executed in a Business Rule triggering Before an operation (e.g. Before creating a user, Before updating a user). Should you still have issues with the script replacing spaces and/or characters, please, provide us with all the possible details regarding the issues. If you face error messages, please, post here or send us (support[at]adaxes.com) screenshots.