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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
confusedphpdev
Forum Newbie
Posts: 2
Joined: Sat May 06, 2017 1:37 pm

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

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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.
confusedphpdev
Forum Newbie
Posts: 2
Joined: Sat May 06, 2017 1:37 pm

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

Post 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.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

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

Post 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.
(#10850)
Post Reply