ak85
ak85

Reputation: 4264

add class to each line of css with regex

I want to add a class at the start of each line of my css

I want

.more {
    padding: 5px 10px 0;
}

#fbook {
    display: inline;
    float: left;
    margin: 0 0 0 4px;
    width: 320px;
}

to look like

.test .more {
    padding: 5px 10px 0;
}

.test #fbook {
    display: inline;
    float: left;
    margin: 0 0 0 4px;
    width: 320px;
}

something like this.

^([A-Za-z0-9]+)$

would work if my css looked like this

more
{
    padding: 5px 10px 0;
}

fbook
{
    display: inline;
    float: left;
    margin: 0 0 0 4px;
    width: 320px;
}

but I can't seem to get anything working when to find the . # {

Upvotes: 2

Views: 91

Answers (2)

Kobi
Kobi

Reputation: 138077

You can use a modern tool like LESS. Simply take your code, and wrap it with .test{ }:

.test {
    .more {
        padding: 5px 10px 0;
    }

    #fbook {
        display: inline;
        float: left;
        margin: 0 0 0 4px;
        width: 320px;
    }
}

If you only need it one time, you can do it online: http://leafo.net/lessphp/#demo
If you want to do it from time to time, there are less libraries for many languages which you can use, and a client side JavaScript option.

Upvotes: 1

Cylian
Cylian

Reputation: 11182

Try this

$result = preg_replace('/(?i)^([.#a-z]+\{)$/m', '.test $1', $subject);

Explanation

"
(?im)         # Match the remainder of the regex with the options: case insensitive (i); ^ and \$ match at line breaks (m)
^             # Assert position at the beginning of a line (at beginning of the string or after a line break character)
(             # Match the regular expression below and capture its match into backreference number 1
   [.#a-z]       # Match a single character present in the list below
                    # One of the characters “.#”
                    # A character in the range between “a” and “z”
      +             # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   \{            # Match the character “{” literally
)
\$             # Assert position at the end of a line (at the end of the string or before a line break character)
"

Upvotes: 2

Related Questions