php - 使用 Regex 解析内联 CSS 值?

标签 php css regex

我有这样的内联 CSS

color:#777;font-size:16px;font-weight:bold;left:214px;position:relative;top:70px

CSS 可以以分号“;”结尾或不。它还可以在其值之间包含额外的空间。我正在使用“explode”函数将 CSS 解析为一个数组,例如:

Array(
"color" => "#777",
"font-size" => "16px",
"font-weight" => "bold",

等等。

谁能建议我使用正则表达式来完成这项任务的方法?

最佳答案

另一种方式,使用正则表达式:

$css = "color:#777;font-size:16px;font-weight:bold;left:214px;position:relative;top:   70px";

$results = array();
preg_match_all("/([\w-]+)\s*:\s*([^;]+)\s*;?/", $css, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
  $results[$match[1]] = $match[2];
}

print_r($results);

输出:

Array
(
    [color] => #777
    [font-size] => 16px
    [font-weight] => bold
    [left] => 214px
    [position] => relative
    [top] => 70px
)

关于php - 使用 Regex 解析内联 CSS 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4432334/

相关文章:

javascript - 将目录路径放在数组中并浏览它们 PHP

php - MYSQL查询问题-想不通

php - 通过 PHP 插入 MYSQL 时的 UNIX 时间戳问题

java - 获取除 to_date 模式之外的绑定(bind)名称

Ruby - 从电子邮件地址中查找文本中的名字和姓氏

php - 在单个 div 中使用两个表

html - :target pseudo selector not selecting target

css - 如何在 visual studio 2010 中设置默认的 css 验证方案?

html - 具有灵活的固定标题行和可滚动主体的表格

Java 正则表达式捕获组索引