代码之家  ›  专栏  ›  技术社区  ›  dom

在php中使用正则表达式替换SASS中的颜色

  •  0
  • dom  · 技术社区  · 9 年前

    我想在这里能够做的是打开一个SASS变量文件,然后在保留格式的同时替换冒号和分号之间的所有内容,在php中,冒号和分号前面有一个特定的选择器字符串,前面的位需要根据php变量进行更改。我似乎能算出一些与上的字符串匹配的正则表达式 RegExr , /\primary-color:(.*?)\; str_replace

    string(328) "// 1. Colors $primary-color: #00c853; $link-color: #ff9800; $secondary-color: #ef6c00; $success-color: green; $error-color: red; $info-color: blue; $warning-color: orange; // 6. Chips $chip-bg-color: #e4e4e4 !default; $chip-border-color: #9e9e9e !default; $chip-selected-color: #26a69a !default; $chip-margin: 5px !default; "
    

    PHP函数

    /**
     * Set Sass Variables
     *
     * @param array $options contains the list of colors to use in the SASS
     */
    public function set_sass_color($option = array()){
      $option['str'] = 'Example Text';
      $option_name = 'primary-color';
      $search = "/\primary-color:(.*?)\;/";
      $variables = file_get_contents(get_template_directory().'/assets/styles/common/_variables.scss');
      $variables_after = str_replace($search,$option['str'],$variables);
      return $variables_after;
    }
    
    1 回复  |  直到 9 年前
        1
  •  0
  •   dom    9 年前

    解决方案

    PHP Live Regex ,这给了我一个更好的工具来计算正则表达式,我改变了 str_replace preg_replace 现在一切似乎都按预期进行。

    /**
     * Set Sass Variables
     *
     * @param array $option contains the option object for modifying the SASS
     */
    public function set_sass_color($option = array()){
      $option['str'] = 'here';
      $option_name = 'primary-color';
      $search = '/('.$option_name.')[:](.*?)[;]/';
      $variables = file_get_contents(get_template_directory().'/assets/styles/common/_variables.scss');
      $variables_after = preg_replace($search,$option['str'],$variables);
      return $variables_after;
    }