John John - 3 months ago 13
Less Question

Parse LESS variables into PHP

Could you help me please:

I have a LESS file with variables, e.g.

/** 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: ~'';


I need to parse this file into PHP and get an array like this:

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


Can this be done with regular expressions or in any another way?

Answer

You can iterate over the input line by line, then split the lines at the :. This should, after some cleaning up, give you the keys and their values.

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