0

I have this line

comment=Accept established chain=forward connection-state=established

And I need to parse it to array. Using explode("=") doesn't work as expected. I get:

array(4) {
  [0]=>
  string(7) "comment"
  [1]=>
  string(24) "Accept established chain"
  [2]=>
  string(24) "forward connection-state"
  [3]=>
  string(11) "established"
}

I tried playing with regex( I suck at it badly). but managed to somehow got to 50%:

preg_match_all("/[([a-zA-Z\-]+=]?/", $line, $result)

which returns:

array(1) {
  [0]=>
  array(3) {
    [0]=>
    string(8) "comment="
    [1]=>
    string(6) "chain="
    [2]=>
    string(17) "connection-state="
  }
}

So it's half way. Now I don't know how to get the string after the "=" part for each line.

1 Answer 1

2

You can use the following regex to parse your string:

([a-z-]+)=(.*?)(?=\s*[a-z-]+=|$)

It looks for some number of a-z or - characters (captured in group 1), followed by an = sign, followed by some (minimal, using ? to make the match lazy) number of characters (captured in group 2) up to either another key followed by = or the end of string. In PHP

$str = 'comment=Accept established chain=forward connection-state=established';
preg_match_all('/([a-z-]+)=(.*?)(?=[a-z-]+=|$)/', $str, $matches);
print_r($matches);

Output (keys are in $matches[1], values in $matches[2]):

Array
(
    [0] => Array
        (
            [0] => comment=Accept established 
            [1] => chain=forward 
            [2] => connection-state=established
        )
    [1] => Array
        (
            [0] => comment
            [1] => chain
            [2] => connection-state
        )
    [2] => Array
        (
            [0] => Accept established 
            [1] => forward 
            [2] => established
        )
)

Demo on 3v4l.org

Note: if the key values could contain uppercase characters, use the i flag on the regex i.e.

preg_match_all('/([a-z-]+)=(.*?)(?=\s*[a-z-]+=|$)/i', $str, $matches);

Also, if you want to generate a key => value array, just use array_combine:

$values = array_combine($matches[1], $matches[2]);
print_r($values);

Output:

Array
(
    [comment] => Accept established
    [chain] => forward
    [connection-state] => established
)
Sign up to request clarification or add additional context in comments.

Comments

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.