gpt4 book ai didi

php - 正则表达式将缺失的选择器添加到无效的 CSS

转载 作者:可可西里 更新时间:2023-11-01 12:36:08 25 4
gpt4 key购买 nike

我正在尝试像这样转换无效的 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

最佳答案

解决方案

你需要使用这个:

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

替换为:

.missing-selector {

(?<=\A|\})确保在 { 之前只有东西(空格除外)是字符串的开头或结尾 } . (感谢 Casimir et Hippolyte 指出那里的问题。)

Here's a regex101 demo .

为什么你的尝试失败了

这个

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

没有按照你的想法去做。

  • (开始一个捕获组
  • [^a-z0-9\)\];\-_]需要 a-z 以外的字符, 0-9 , ) , ] , ; , - , 或 _
  • *零次或多次
  • \{需要 {
  • )结束捕获组

但它没有 ^ , 所以它不依赖于行的开头,也不验证 { 之前的任何内容(这应该只是字符串、空格或 } 的开头)。因此,它将匹配示例 CSS 中包含一系列空格或其他非字母数字字符(不包括 )];-_ )的所有位置:

screenshot of regex101 demo

See this regex101 demo for a fuller explanation and example matches .

关于php - 正则表达式将缺失的选择器添加到无效的 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35659298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com