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?
$retrieved_string = 'some unformatted string; it may contain illegal characters to be passed as a class name.';
$strMyScript = basename(__FILE__, ".php");
$strMyScript = sanitize_variable($strMyScript);
$strClassName = sanitize_variable($retrieved_string);
eval('
class ' . $strMyScript . '_' . $strClassName . ' extends AnotherClass {
// some code here
}
');
funaction sanitize_variable($string) {
// sanitize the string
}
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.
You might also want to check for unicode. The pattern is:
Issues also to consider:
HTH