1

我有以下模式:

[\{\}].*[\{\}]

使用以下测试字符串(如果需要可以提供更多):

}.prop{hello:ars;} //shouldn't match
}#prop{} //should match
}.prop #prop {} //should match

该模式的目的是找到空的 CSS 规则集。有人可以建议我如何排除与第二组括号之间的字符匹配的内容吗?随着我越来越接近解决方案,我将更新模式。

编辑:在http://gskinner.com/RegExr/ 这个模式:[\}].*[\{]{1}[/}]{1} 似乎有预期的结果,尽管由于我不明白的原因转移到 php 时它会中断。

编辑:如果这应该是一个单独的问题,首先道歉。在 php 的第一次编辑中使用模式:

    $pattern = "/[\}].*[\{]{1}[/}]{1}/";
    preg_match_all ($pattern, $new_css, $p);
    print_r($p);

当 $new_css 是包含空规则集的上传 css 文件的内容字符串时,永远不会填充 $p。然而我知道这种模式是可以的。任何人都可以看到问题是什么?

编辑:最终解决方案

//take out other unwanted characters
        $pattern = "/\}([\.#\w]\w+\s*)+{}/";
        //do it twice to beat any deformation
        $new_css = preg_replace ($pattern, '}', $new_css);
        $new_css = preg_replace ($pattern, '}', $new_css);
4

2 回答 2

1

尝试在正则表达式周围使用单引号,或将\字符加倍。PHP\在双引号字符串中的处理方式是\{变成{,打破了正则表达式。

于 2012-07-18T16:40:10.760 回答
0

试试这个模式:'/}([\.#]\w+\s*)+{}/'

$new_css = "{}.prop{hello:ars;}
{}#prop{} //should match
}.prop #prop {} //should match
}.prop { aslkdfj}
}.prop { }
";

$pattern = '/}([\.#]\w+\s*)+{}/';
preg_match_all ($pattern, $new_css, $p);
print_r($p);

这输出:

Array
  (
    [0] => Array
    (
      [0] => }#prop{}
      [1] => }.prop #prop {}
    )

    [1] => Array
    (
      [0] => #prop
      [1] => #prop
    )
  )
于 2012-07-18T17:26:25.400 回答