Posted by tim in I hate technology. on November 2, 2022

For years (more than 20) I have been doing things the long way with PHP. One of the examples of this is processing files and putting the results in an array (or object) to serve as key/value pairs.

Consider the following:

Foo: bar
Baz: biz

Here's some content...

If you wanted to match these lines in a way that you only get the Foo: bar and Baz: biz into a key/value pair, you would need to somehow match those values into a variable. Something like this would work:

<?php
preg_match_all('/^(.*?): (.*?)$/m', file_get_contents($filename), $matches);

But this will give you something like this: Array ( [0] => Array ( [0] => Foo: bar [1] => Baz: biz )

    [1] => Array
        (
            [0] => Foo
            [1] => Baz
        )

    [2] => Array
        (
            [0] => bar
            [1] => biz
        )

)

But what if you want to have the matched group [1] be the keys, and matched group [2] be the values? A for loop would accomplish it, as would other array-walking techniques.

It's far easier than that, though!

<?php
preg_match_all('/^(.*?): (.*?)$/m', file_get_contents($filename), $matches);

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

If you print_r() that resultant variable, you'll find that it's exactly what you want:

Array
(
    [Foo] => bar
    [Baz] => biz
)

That's all I wanted to share. I hope it benefits you.

  • Add a comment!
Copyright © 2024 SkuddBlog