Page 1 of 1

How do I create an array from substrings in a text string?

Posted: Sat May 06, 2017 2:12 pm
by confusedphpdev
I've been stuck on this for hours so I'm finally asking for help. I'm not sure if I'm going about this correctly but I have a text file that looks something like this:

Code: Select all


[Beginning]
ABC
[Ending]

[Beginning]
DEF
[Ending]


[Beginning]
GHI
[Ending]


[Beginning]
JKL
[Ending]

[Beginning]
MNO
[Ending]

You get the point. I've been trying to use strpos, substr, looked at preg_match but I am just really confused and lost at this point.

I want to be able to create 2 different arrays from this data.

One array like this:

Code: Select all


$array1 = array(
         "ABC",
         "DEF",
         "GHI",
          "JKL",
          "MNO"
);


And another array like this:

Code: Select all


$array2 = array(

"[Beginning]
ABC
[Ending]",


"[Beginning]
DEF
[Ending]",


"[Beginning]
GHI
[Ending]",


"[Beginning]
JKL
[Ending]",

"[Beginning]
MNO
[Ending]"

);

This way I can use foreach loops to process these arrays as needed.

Re: How do I create an array from substrings in a text strin

Posted: Sat May 06, 2017 2:23 pm
by requinix

Code: Select all

preg_match_all('/^' . preg_quote('[Beginning]') . '[\r\n]+(.*)[\r\n]+' . preg_quote('[Ending]') . '$/m', $string, $matches)
can give you exactly that.

Re: How do I create an array from substrings in a text strin

Posted: Sat May 06, 2017 5:21 pm
by confusedphpdev
Thanks this worked fine on the link you posted but when I run the code on my server it only returns the last set of data and doesn't give me any of the other results.

Re: How do I create an array from substrings in a text strin

Posted: Sat May 06, 2017 7:37 pm
by Christopher
If you want to generate both arrays in one pass, you may want read file into an array (readfile() I think) and then loop through looking for "[Beginning]" and "[Ending]". You'll need a counter for the arrays you are writing to and another var to track state.