Sass 来自 PHP 的变量值匹配(可能是正则表达式)
Sass Variable Value Matching from PHP (likely a Regex)
我需要 get/set 来自 Scss 变量文件 PHP 的 Scss 变量值。
直接进入示例:
// $mainColor: #fafafa;
//$mainColor : #a375c1;
$mainColor: #b3e287;
$mainColor: #ac3190; // <- This is the value I'd like to grab/set
$boxColor: ligthen($mainColor, 10%);
从这样的文件中,(我事先知道变量名)我希望能够从第 4 行 get/set 变量,现在问题在于我需要忽略变量,如果它被评论,或者之后如果它没有被赋值。我认为最好的方法是结合使用 strpos 和 Regex,我只是对 regex 了解不够,无法正确使用负前瞻,也无法找到变量赋值的最后一次迭代。
一旦我匹配了变量,我就很容易得到 clean/trim 值,不需要匹配是否是十六进制,只要真正抓住 :
和 :
之间的任何东西;
所以再一次,变量名是已知的。
以下代码片段有效,展示了如何完成您所要求的大部分内容。
<?php
$contents = file('file.scss'); //array with lines from file
$linenum = 0;
foreach($contents as $key=>$line)
{
// a line can start with 0 or more spaces, then // (maybe, maybe not), then 0 or more space, then something entirely unknown, then a : then something entirely unknown and then a ;
//[0] = the whole line [1] = the // or not [2] is the variablename [3] = the variabel value
if (preg_match('/[ ]*([\/]{2})?[ ]*(.*?):(.*?);/is', $line, $matches))
{
$variablename = $matches[2];
$variablevalue = $matches[3];
if ($variablename == '$myvar')
{
if ($matches[1] != '//') //if it is not commented out
$contents[$key] = '$mainColor: red;'; //replace the whole line, if you want to replace only the color you can maybe use str_replace to replace the $variablevalue to something else?
//$contents[$key] = str_replace($variablevalue, 'red', $line); // this line is untested
break;
}
}
}
//do something with the result:
echo implode($contents);
编辑:我在评论后更改了脚本。
我需要 get/set 来自 Scss 变量文件 PHP 的 Scss 变量值。
直接进入示例:
// $mainColor: #fafafa;
//$mainColor : #a375c1;
$mainColor: #b3e287;
$mainColor: #ac3190; // <- This is the value I'd like to grab/set
$boxColor: ligthen($mainColor, 10%);
从这样的文件中,(我事先知道变量名)我希望能够从第 4 行 get/set 变量,现在问题在于我需要忽略变量,如果它被评论,或者之后如果它没有被赋值。我认为最好的方法是结合使用 strpos 和 Regex,我只是对 regex 了解不够,无法正确使用负前瞻,也无法找到变量赋值的最后一次迭代。
一旦我匹配了变量,我就很容易得到 clean/trim 值,不需要匹配是否是十六进制,只要真正抓住 :
和 :
之间的任何东西;
所以再一次,变量名是已知的。
以下代码片段有效,展示了如何完成您所要求的大部分内容。
<?php
$contents = file('file.scss'); //array with lines from file
$linenum = 0;
foreach($contents as $key=>$line)
{
// a line can start with 0 or more spaces, then // (maybe, maybe not), then 0 or more space, then something entirely unknown, then a : then something entirely unknown and then a ;
//[0] = the whole line [1] = the // or not [2] is the variablename [3] = the variabel value
if (preg_match('/[ ]*([\/]{2})?[ ]*(.*?):(.*?);/is', $line, $matches))
{
$variablename = $matches[2];
$variablevalue = $matches[3];
if ($variablename == '$myvar')
{
if ($matches[1] != '//') //if it is not commented out
$contents[$key] = '$mainColor: red;'; //replace the whole line, if you want to replace only the color you can maybe use str_replace to replace the $variablevalue to something else?
//$contents[$key] = str_replace($variablevalue, 'red', $line); // this line is untested
break;
}
}
}
//do something with the result:
echo implode($contents);
编辑:我在评论后更改了脚本。