Developer Gee
Developer Gee

Reputation: 402

How do I process text file into an array?

I have a series of text files that I need to be able to process into an array in order to further process the data and insert it into a database. I can handle the end processing and mysql.

Here is where I am stuck, I am guessing it is some regular expressions magic, which is a weak point for me.

I have a text file with the contents like this:

[Section 1]
Key:Value
Key:Value
Key:Value
Key:Value

[Section 2]
Key:Value
Key:Value

I need to put it into an array where it is broken apart into something like

Array
(
[Section 1] => Array
    (
        [0] => Key:Value
        [1] => Key:Value
        [2] => Key:Value
        [3] => Key:Value
    )

[Section 2] => Array
    (
        [0] => Key:Value
        [1] => Key:Value
        [2] => Key:Value
    )

[Section 3] => Array
    (
        [0] => Key:Value
        [1] => Key:Value
    )

)

I can handle the last part of the array, I just can't figure out the first part of detecting the brackets and breaking it up from there

Upvotes: 1

Views: 81

Answers (2)

lsouza
lsouza

Reputation: 2488

You could do it without a regex, like this:

$lines = explode(PHP_EOL, $text);
$sections = array();
$section = '';

foreach ($lines as $line) {
    if (!trim($line)) continue;

    if ($line{0} == '[') {
        $section = trim(preg_replace("/\[(.+)\]/", "$1", $line));
    } else {
        $sections[$section][] = $line;
    }
}

Upvotes: 0

Explanation :

The file is opened and read into an array using file(). Each elements of the array are looped and checked if it contains a [ , If it does.. We do a preg_match() and grab the text between the square brackets.. say Section 1 which is then added inside a temp variable $key.

And on successive iterations.. the elements will be added to the above key... and again if it encounters a [ the above step will be taken into account.

<?php
$arr = file('somefile.txt',FILE_IGNORE_NEW_LINES);
$key="";
foreach($arr as $line)
{
    if(strpos($line,'[')!==false)
    {
        preg_match('@\[(.*?)\]@', $line, $matches);
        $key = trim($matches[1]);
    }
    else if(!empty($line))
    {
        $new_arr[$key][]=$line;
    }
}

print_r($new_arr);

Upvotes: 4

Related Questions