gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:11:20 25 4
gpt4 key购买 nike

我有这样的内联 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com