用Regex解析内联CSS值? [英] Parse inline CSS values with Regex?

查看:223
本文介绍了用Regex解析内联CSS值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的内联CSS


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


CSS可能以分号或不。它还可以在其值之间包含额外的空间。我使用explode函数将CSS解析为数组,如:


数组(

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);

输出:

 
数组

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


I have such an inline CSS like this

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

The CSS may end with a semicolon ";" or not. It also can contain extra space between its values. I'm about using "explode" function to parse the CSS into an array, something like :

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

and so on.

Can anybody suggest me a way to use regular expression to complete this task?

解决方案

Another way, using a regex:

$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);

Outputs:

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

这篇关于用Regex解析内联CSS值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆