php 解析 css class 字符串

php parse css class string

我需要获取 css class 名称、属性和值,以便将内联 css 样式应用于 div。 目前,我可以从这样的字符串中检索 css class 名称信息:

$class = ".custom_class {
    margin-top: 0px !important;
    border-top-width: 0px !important;
    border-right-width: 0px !important;
    border-left-width: 0px !important;
    padding-top: 250px !important;
    padding-bottom: 250px !important;
    background-image: url(http://localhost/wordpress/wp-content/uploads/2015/01/old-car.jpg?id=3663) !important;
    border-left-color: #dd3333 !important;
    border-right-color: #dd3333 !important;
    border-top-color: #dd3333 !important;
}";

如何获取或正则表达式所有 css 属性和值,以便将它们包含在 div 中,如下所示:

<div class="custom_class" style="margin-top: 0px !important;border-top-width: 0px !important;border-right-width: 0px !important;border-left-width: 0px !important;padding-top: 250px !important;padding-bottom: 250px !important;background-image: url(http://localhost/wordpress/wp-content/uploads/2015/01/old-car.jpg?id=3663) !important;border-left-color: #dd3333 !important;border-right-color: #dd3333 !important;border-top-color: #dd3333 !important;"></div>

我试过这个:preg_match("/{(.*?)}/", $class, $match); 但它输出带括号。对于 class 这个名字,我不知道该怎么做。

您使用正则表达式 preg_match("/{(.*?)}/", $class, $match);,只需转义大括号并检索 $match[1]:

中的数据
preg_match("/^([\w.]+)\s*\{(.*?)\}/s", $class, $match);
$classname = $match[1];
$style = $match[2];