在PHP中清理用户定义的CSS,可以使用以下方法:
$user_css = "body {background-color: red;}";
$clean_css = preg_replace('/[^a-zA-Z0-9\s\.,:;#\(\)\[\]]/', '', $user_css);
php-css-parser
,将用户定义的CSS解析为对象,然后遍历对象并删除不需要的属性和选择器。require_once('vendor/autoload.php');
use Sabberworm\CSS\Parser;
$user_css = "body {background-color: red;}";
$parser = new Parser($user_css);
$css = $parser->parse();
// 遍历CSS对象并删除不需要的属性和选择器
foreach ($css->getAllDeclarationBlocks() as $declarationBlock) {
foreach ($declarationBlock->getSelectors() as $selector) {
if (/* 判断选择器是否需要删除 */) {
$declarationBlock->removeSelector($selector);
}
}
foreach ($declarationBlock->getRules() as $rule) {
if (/* 判断属性是否需要删除 */) {
$declarationBlock->removeRule($rule);
}
}
}
// 将清理后的CSS转换为字符串
$clean_css = $css->render();
$allowed_selectors = ['body', 'h1', 'h2', 'p'];
$allowed_properties = ['color', 'background-color', 'font-size'];
$user_css = "body {background-color: red;}";
$clean_css = '';
foreach ($allowed_selectors as $selector) {
$clean_css .= $selector . ' {' . "\n";
foreach ($allowed_properties as $property) {
$clean_css .= "\t" . $property . ': ' . $user_css[$selector][$property] . ";\n";
}
$clean_css .= '}' . "\n";
}
以上方法可以帮助您在PHP中清理用户定义的CSS,以确保安全性和可控性。
领取专属 10元无门槛券
手把手带您无忧上云