0

如何在 php 中使用 sass 之类的变量提取键值对?

$blue: #3bbfce;
$margin:16px;

结果应如下所示:

array('blue' => '#3bbfce', 'margin' => '16px'); 

其次,如何删除(剥离)css 样式表中的所有/任何变量声明?

4

1 回答 1

6
<?php
$subject = '$blue: #3bbfce; \n $margin:16px;';
$pattern = '/\$(.*?):(.*?);/';

preg_match_all($pattern, $subject, $matches);
$variableArray = array_combine( $matches[1], $matches[2] );
array_map( function($val) { return ltrim($val); }, $variableArray );
print_r($variableArray);

This will net you the result you're looking for. To get rid of all such definitions, just use preg_replace over the subject with the same $pattern. Basically, what this regular expression says is

  • Find anything starting with a $ that...
    • Is followed by an arbitrary set of characters, then a colon and another arbitrary set of characters followed by a semicolon.

You might want to refine this pattern using character classes like to so you won't match variables like $this is not a valid variable: name.

于 2012-09-09T01:27:27.320 回答