0

I have a config file which structure looks like this:

#comment1
key1 value1

#comment2
key-key2 value2

#comment3
key3 value3 value4

I have been trying to parse this in PHP with the following code:

$lines = explode(PHP_EOL, $string);
$config = [];

foreach ($lines as $l) {
    preg_match("/^(?P<key>\w+)\s+(?P<value>.*)/", $l, $matches);

    if (isset($matches['key'])) {
        $config[$matches['key']] = $matches['value'];
    }
}

However I am not able to get the regex right, the above regex is only functioning for the line with #comment1, it does not parse key-key2 properly and #comment3 key-value has 2 values which should just be 1 string inside the array.

Output I wish to have:

[
   'key1' => 'value1',
   'key-key2' => 'value2',
   'key3' => 'value3 value4'
]

Anyone able to help me with the regex?

7
  • How do you read the file? Big blob or line by line Commented Sep 5, 2019 at 13:23
  • Line by line (I am exploding on PHP_EOL (newline) in the string content) Commented Sep 5, 2019 at 13:23
  • So $lines is in fact just a single line ? Commented Sep 5, 2019 at 13:25
  • $lines is the array, and I foreach through it, $l is the line itself inside the foreach. Commented Sep 5, 2019 at 13:25
  • You might want to just explode the line on space and check that count = 2. Commented Sep 5, 2019 at 13:26

2 Answers 2

2

It should be simple enough not to have to use regex as you can check for # at the start of the line easily enough and then use explode() with a space and limit of 2 parts to extract the key and data...

$lines = explode(PHP_EOL, $string);
$config = [];

foreach ($lines as $l) {
    if ( !empty($l) && $l[0] != '#' ) {
        list($key, $value) = explode(" ", $l, 2);
        $config[$key] = $value;
    }
}
print_r($config);
Sign up to request clarification or add additional context in comments.

1 Comment

Great solution actually, never thought of this. Thank you!
1

Using your existing code; just explode each line on space limiting to 2 elements and check that you get 2 elements:

$lines = explode(PHP_EOL, $string);

foreach ($lines as $l) {
    if(count($parts = explode(' ' , $l, 2)) == 2) {
        $config[$parts[0]] = $parts[1];   
    }
}

1 Comment

This has problems when the comment has a space in it.

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.