Sanitize Strings for Legal Variable Names in PHP

I have code something like the following, which declares a class and its name is based on a retrieved string. But the problem is that the string may contain illegal characters that PHP doesn't accept as a class name. So is there a good way to sanitize the string before using it as a class name?

Answers

First decide what you need a filter or a validator. A validator will return true/false. Then you can raise an exception, produce an error for the user or just ignore the file. The other option is to use a filter which will effectively remove characters from the input string.

If you're looking to sanitize the string, then maybe you need to remove everything that's not [a-zA-Z0-9_\x7f-\xff] and then validate against ^([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$ (the difference is, while integers are allowed characters, a class/function name may not start with one).