Capturing newline with regexp at end of css selector?

Discussion in 'Programming' started by carlos123, Oct 16, 2009.

  1. #1
    I am trying to capture the newline at the end of a CSS file selector so that I can insert a new CSS property but am having a real tough time doing so...

    Let's say I have this...

    
    body {
       width: 100px;
       height: 100px;
    }
    
    Code (markup):
    And I want it to end up like this...

    
    body {
       background: url("some-image.png") repeat-x;
       width: 100px;
       height: 100px;
    }
    
    Code (markup):
    Here is what I have so far...

    
    $text = preg_replace('/
       (body\s+{\n?)
       (.*?})
       /sx', '$1   background: url("some-image.png") repeat-x;$2', $text);
    
    Code (markup):
    $text is a variable into which I have read the CSS file as it exists before the change desired.

    The 3 spaces before each property inside the body selector can either be spaces or tabs.

    How do I capture the ending newline in the first capture such that $1 will insert everything in the first capture (including the newline) back into the replacement string?

    Anybody got any suggestions?

    Carlos
     
    carlos123, Oct 16, 2009 IP
  2. ccoonen

    ccoonen Well-Known Member

    Messages:
    1,606
    Likes Received:
    71
    Best Answers:
    0
    Trophy Points:
    160
    #2
    \r\n maybe? It could be combo (which is chr 10 + 13)
     
    ccoonen, Oct 16, 2009 IP
  3. carlos123

    carlos123 Peon

    Messages:
    58
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks ccoonan.

    I finally figured it out though I am not sure I fully understand why it works.

    
    $text = preg_replace('/
    (
    body
    \s*    # match 0 or more spaces
    {
    .*     # match 0 or more characters including newlines as a result of the s modifier
    )
    }
    /Usx', '$1'."\n   background: url(".parent::$pageBackground.") repeat-x;\n   }", $text);
    
    Code (markup):
    Carlos
     
    carlos123, Oct 16, 2009 IP