string parsing help

Posted by sprugman on Stack Overflow See other posts from Stack Overflow or by sprugman
Published on 2010-05-24T22:58:33Z Indexed on 2010/05/24 23:01 UTC
Read the original article Hit count: 244

Filed under:
|
|

I've got a string like this:

####################
Section One
####################
Data A
Data B


####################
   Section Two
####################
Data C
Data D

etc.

I want to parse it into something like:

$arr(
    'Section One' => array('Data A', 'Data B'),
    'Section Two' => array('Data C', 'Data D')
)

At first I tried this:

$sections = preg_split("/(\r?\n)(\r?\n)#/", $file_content);

The problem is, the file isn't perfectly clean: sometimes there are different numbers of blank lines between the sections, or blank spaces between data rows.

The section head pattern itself seems to be relatively consistent:

####################
   Section Title
####################

The number of #'s is probably consistent, but I don't want to count on it. The white space on the title line is pretty random.

Once I have it split into sections, I think it'll be pretty straightforward, but any help writing a killer reg ex to get it there would be appreciated. (Or if there's a better approach than reg ex...)

© Stack Overflow or respective owner

Related posts about php

Related posts about regex