1

I have the following pattern:

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

With the following test strings (can provide more if needed):

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

The purpose of the pattern is to find empty css rulesets. Can someone suggest how I go about excluding matches with characters between the second set of brackets? I will be updating the pattern as I get closer to a solution.

edit: on http://gskinner.com/RegExr/ this pattern: [\}].*[\{]{1}[/}]{1} seems to have the desired result although it is breaking when transfered to php for reasons I don't understand.

edit: first apologies if this should be a separate question. Using the pattern in the first edit in php:

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

When $new_css is a string of the content of an uploaded css file containing empty rulesets, $p is never populated. Yet I know this pattern is ok. Can anyone see what the issue is?

edit: final solution

//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);
3
  • Why does \{\s*\} not work? Commented Jul 18, 2012 at 16:07
  • I want to get the class / id ect as well as the brackets Commented Jul 18, 2012 at 16:14
  • Last year I did something similar in php with .css files, removed all comments, tokenized the text and detected all color definitions. So I am also curious if somebody will help you to find some solution. Commented Jul 18, 2012 at 16:30

2 Answers 2

1

Try using single quotes around the regex, or doubling the \ characters. The way PHP handles \ in double-quoted strings is that \{ becomes {, breaking the regex.

Sign up to request clarification or add additional context in comments.

Comments

0

Try the pattern: '/}([\.#]\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);

This outputs:

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

    [1] => Array
    (
      [0] => #prop
      [1] => #prop
    )
  )

2 Comments

Sorry for the delayed response. The pattern is slightly too restrictive and only captures the first class/id name. It fails on more complex selectors. I will see if I can adjust it.
correction to the above, it does not capture native elements such as body, ul, li ect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.