Search code examples
phppreg-match

preg_match regexp syntax extracting up to ;


I have a file containing key/value pairs with on occasional comment (delimited by a ';') that a want to parse with preg_match (or maybe preg_match is the wrong tool).

The file looks like this

  key1 VALUE1
  key2 VALUE2 ; comment 2
  key3 VALUE3a VALUE3b
  key4 VALUE4a VALUE4b ; comment 4

(there is one or more whitespaces at the beginning of each line)

My preg_match looks like this preg_match('/\s*(\S+)\s+(.+)/', $line, $result); which correctly splits the lines "key1" and "key3". For key2 and key4 the "; comment #" becomes part $result[2]. Is it possible "remove" the ";comment" part directly in the preg_match (I do not care if the "; comment" part ends up in $result[3].


Solution

  • you can do it using this regex :

    \s*(\S+)\s+([^;]+)
    

    see there