将LESS变量解析为PHP

时间:2016-09-04 09:52:35

标签: php regex parsing less

请你帮帮我吧。

我有一个带变量的LESS文件,例如

/** preloader colors **/
@preloader_bg: #0081ff;
@preloader_color: #fff;

/** layout **/
@body_bg_image_position: ~'left top';
@body_bg_image_repeat: ~'no-repeat';
@body_bg_image_cover: ~'auto';
@body_bg_image: ~'';

我需要将此文件解析为PHP并获取如下数组:

$less_vars = array(
  'preloader_bg' => '#0081ff',
  'body_bg_image_position' => 'left top'
);

这可以用正则表达式还是以其他方式完成?

2 个答案:

答案 0 :(得分:1)

您可以逐行迭代输入,然后在:处拆分行。经过一些清理后,这应该给你钥匙和价值。

See the ideone

$input = "
/** preloader colors **/
@preloader_bg: #0081ff;
@preloader_color: #fff;

/** layout **/
@body_bg_image_position: ~'left top';
@body_bg_image_repeat: ~'no-repeat';
@body_bg_image_cover: ~'auto';
@body_bg_image: ~'';
";

// create an array to store the values
$cssVar = [];

// iterate over the lines
foreach (split("\n", $input) as $ln) {
    // ignore lines that don't start with @ as they are not variables
    if ($ln[0] != "@") {
        continue;
    }
    // get the key and value for the css variable
    // TODO: cleanup ~ mark
    $bits = explode(":", $ln);
    $key = substr(trim($bits[0]), 1);
    $value = trim($bits[1]);

    // store the value
    $cssVar[$key] = $value;
}

var_export($cssVar);

答案 1 :(得分:1)

你也可以使用一个RegEx:

^@([^:]+):[~\s]*(['\"]?)([^;]*)\\2;?$

PHP(this):

preg_match_all("/^@([^:]+):[~\s]*(['\"]?)([^;]*)\\2;?$/m", $str, $matches);
var_dump(array_combine($matches[1], $matches[3]));

输出:

array(6) {
  ["preloader_bg"]=>
  string(7) "#0081ff"
  ["preloader_color"]=>
  string(4) "#fff"
  ["body_bg_image_position"]=>
  string(8) "left top"
  ["body_bg_image_repeat"]=>
  string(9) "no-repeat"
  ["body_bg_image_cover"]=>
  string(4) "auto"
  ["body_bg_image"]=>
  string(0) ""
}