2015-02-08 46 views
0

如何用PHP减少CSS /(或)LESS? 从这:如何将CSS减少到几个属性

.header-logo-holder{ 
    display: block; 
    float: none; 
    text-align: center; 
    margin: 10px 0; 
    color: #fff; 
    background: #333; 
    padding-bottom: 15px; 
    border-bottom: 1px solid darken(@rw-header-background-color, 10%); 
    .logo{ 
     margin: 0; 
    } 
    .eg-clearfix(); 
} 

要这样:

.header-logo-holder{ 
    color: #fff; 
    background: #333; 
    border-bottom: 1px solid darken(@rw-header-background-color, 10%); 
} 

我想离开只是规则的颜色,背景和边框。

+0

如果我理解正确的话,你有第一个CSS,但要删除通过PHP一些线路? – ikhebgeenaccount 2015-02-08 14:03:25

+0

是的。那就对了。 – 2015-02-08 14:05:24

+0

为什么你想用PHP删除CSS?如果你的CSS/Less是分开的(它应该是),你可以在CSS/Less中删除CSS。 – 2015-02-08 14:21:34

回答

2

这里是我的解决方案:

<?php 

//give the file (string) to the function 
function keepColorBackgroundBorder($input) { 

    //didn't check if the input was correct (string, not empty, etc) 

    //we turn the input into an array 
    $input = explode("\n", $input); 

    //here is the list of strings which must be in a line to keep it in our final string 
    $keep = ['{', '}', 'color', 'background', 'border']; 

    $result = ''; 

    //foreach over the lines of the input 
    foreach ($input as $key => $value) { 

     //foreach over each characters we want to keep 
     foreach ($keep as $key => $value2) { 

      //if the characters are somewhere in the line 
      if (strpos($value, $value2) !== false) { 

       //we add the line + a newline character 
       $result .= $value . "\n"; 

       //we stop the check for characters as we don't want a line to be included twice 
       //e.g: border-bottom: 1px solid darken(@rw-header-background-color, 10%); 
       //this example contains border and background 
       break; 
      } 
     } 
    } 

    //we return the result, end delete the last newline character 
    return trim($result); 
} 

//we get the file as a string 
$input = file_get_contents('file.css'); 

//we call the function and we look at what was outputted 
echo keepColorBackgroundBorder($input); 

有可能是过多评论,但它比不够好太多。

我使用了一个数组,以便在需要时可以轻松更改。例如,您可以让['background:', 'border:', 'border-bottom:']等确保不包含行,如果它包含允许的字在其他地方不在开始处,如border-bottom: 1px solid darken(@rw-header-background-color, 10%);其中包含background,但不包括background:

如果file.css包含:

.header-logo-holder{ 
    display: block; 
    float: none; 
    text-align: center; 
    margin: 10px 0; 
    color: #fff; 
    background: #333; 
    padding-bottom: 15px; 
    border-bottom: 1px solid darken(@rw-header-background-color, 10%); 
    .logo{ 
     margin: 0; 
    } 
    .eg-clearfix(); 
} 

您将获得:

.header-logo-holder{ 
    color: #fff; 
    background: #333; 
    border-bottom: 1px solid darken(@rw-header-background-color, 10%); 
    .logo{ 
    } 
} 
+0

它看起来不错。我自己也找到了解决方案,但仍需要手动删除一些元素。这与你的非常相似。 :)谢谢你的帮助,反正。 ;)干杯。 – 2015-02-08 18:23:01

+0

@Smartik乐于助人。编辑我的答案,添加一些细节。我不知道* LESS *,但我不认为'.logo {}'实际上不是问题。 – tleb 2015-02-08 18:33:32