[regex] How to capture everything until match a string

Discussion in 'PHP' started by Romain, Apr 13, 2008.

  1. #1
    Hello,

    If I use ([^string]+) in a regex, it will capture everything until it matches any s, t, r, i, n or g, right?

    how to capture everything until it matches the whole string as a... string ?
    Logically I would have done this: ([^(?:string)]+) but it doesn't seem to work..


    thanks for your help :)
     
    Romain, Apr 13, 2008 IP
  2. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #2
    Lookahead assertions.

    <?
    $str1 = 'stay out of the weed';
    $str2 = 'stay out of the weeds';
    $pattern = '#^(.+(?=weeds?))#si';
    $matches = array();
    
    preg_match($pattern, $str1, $matches[0]);
    preg_match($pattern, $str2, $matches[1]);
    
    echo sprintf('<pre>%s</pre>', print_r($matches, true));
    ?>
    Code (markup):
     
    joebert, Apr 14, 2008 IP
  3. Romain

    Romain Peon

    Messages:
    20
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks a lot, I didn't know about assertions!
     
    Romain, Apr 14, 2008 IP
  4. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #4
    They're kinda confusing at first.
    One thing that gets me sometimes is remembering to use the occurance specification before the assertion.
    .+(?=ahead)
    
    // instead of 
    
    .(?=ahead)+
    Code (markup):
    I think the error it gives me is something along the lines of "Nothing to repeat at index X".
     
    joebert, Apr 15, 2008 IP