2016-02-26 33 views
8

我試圖改變無效的CSS是這樣的:正則表達式來添加缺少的選擇無效CSS

{color:red}

,並使其有效像這樣:

.missing_selector{color:red}

範例CSS:

a { 
color:black; 
background-color:blue; 
} 

{color:red} 
<!-- TEST --> 

@media screen and (max-width:620px) { 
/* TEST 2 */ 
a.test {color:blue;} 
p[class="test2"] {color:green;} 
} 

我目前正則表達式:

/([^a-z0-9\)\];\-_]*\{)/i

現場測試:

http://www.phpliveregex.com/p/eMq

+0

只是一個提示,而不是答案,但也許這個庫可以幫助:https://github.com/sabberworm/PHP-CSS-Parser我想,僅僅使用正則表達式的解決方案相當容易出錯。 – Jan

+0

您可以嘗試['/^\h*\K(?={)/m'](https://regex101.com/r/mC7pI5/1)並替換爲'.missing_selector' –

回答

6

解決方案

您需要使用這樣的:

/(?<=\A|\})(\s*)\{/m 

替換爲:

.missing-selector { 

(?<=\A|\})可確保那裏的{之前唯一(除空白,)是字符串或關閉}的開始。 (感謝Casimir et Hippolyte因爲有指出的問題。)

Here's a regex101 demo

爲什麼你嘗試失敗

/([^a-z0-9\)\];\-_]*\{)/i 

不會做你的想法。

  • (開始捕獲組
  • [^a-z0-9\)\];\-_]需要比a-z0-9)];-,或_
  • *零次或多次
  • \{要求{
  • 以外的字符
  • )結束捕獲組

但它不具有^,所以它不依賴於行的開始,也沒有驗證{之前,無論發生什麼事(這應該是唯一的字符串的開始,空格或})。其結果是,它會匹配所有的東西你在你的樣品CSS有一系列的空格或(不含)];-_)其他非字母數字字符:

screenshot of regex101 demo

See this regex101 demo for a fuller explanation and example matches

+0

謝謝@EdCottrell,this正是我所需要的。我也很欣賞這個解釋。 – user2266497