Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
来自PHP的Sass变量值匹配(可能是正则表达式)_Php_Regex_String Matching - Fatal编程技术网

来自PHP的Sass变量值匹配(可能是正则表达式)

来自PHP的Sass变量值匹配(可能是正则表达式),php,regex,string-matching,Php,Regex,String Matching,我需要从一个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%); /$mainColor:#fafafa; //$main

我需要从一个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%);
/$mainColor:#fafafa;
//$mainColor:#a375c1;
$mainColor:#b3e287;

$mainColor:#ac3190;// 下面的代码片段正在运行,它展示了如何完成您要求的大部分工作

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

A每行
strpos()
,问题是从中过滤掉注释或非赋值语句,也不确定每行
strpos()
在整个文件上的性能是否比正则表达式差(尽管在这种情况下性能根本不重要)。类似这样的情况<代码>$result=preg_grep(“/$mainColor:(#.{6};)/”,文件($sass_文件_路径))
稍后会对此进行测试,但不确定
$linenum
变量的用途是什么?请求
$linenum==4
是为了查找第4行,我提供的是一个示例文件,格式如下,但要长得多,变量可以放在任何一行并随时更改。但是有了这段代码,我可能可以对它进行转换以满足我的要求。@Sandman21dan我想你想更改第4行的变量。我更改了答案中的脚本,使其位于任意一行,但变量名匹配
$linenum
仅用于获取第4行并跳过空行。我还稍微调整了正则表达式。这很有效!一个问题是确认后的
break
语句是一个变量,因为即使找到的是注释,它也会停止算法,因此,在评估该行不是注释后,我构建了一个结果数组,最后一个元素(将包含要使用的实际颜色)是我必须替换的元素。不过,正则表达式工作得非常好,这正是我想要的。谢谢