我有类似下面的代码,它声明了一个类,它的名称基于检索到的字符串。但问题是字符串可能包含 PHP 不接受作为类名的非法字符。那么有没有一种在将字符串用作类名之前对其进行清理的好方法?
$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
}