user2441938
user2441938

Reputation: 145

PHP Regex finding blocks of text seperated by two line breaks

I'm new to regex and having some issues with it.

I have a text file with blocks of text that I want to put into an array. Each text block starts with "Hand #" and ends with "** Deck **" and is separated by line breaks. It looks like something like this:

Hand #...random digits
blah
blah
blah
blah
** Deck **...random digits

Hand #...random digits
blah
blah
blah
blah
** Deck **...random digits

Hand #...random digits
blah
blah
blah
blah
** Deck **...random digits

I want each array element to include the text between each pair of "Hand #" and "** Deck **". What i've tried so far which isn't returning any results:

preg_match_all("%Hand #(.*?)[*][*] Deck [*][*]%", $file, $array);

Thanks for the help!

Upvotes: 1

Views: 71

Answers (1)

Martin Ender
Martin Ender

Reputation: 44259

. by default does not match line breaks. You can change this with the s (singleline or "dotall") modifier:

preg_match_all("%Hand #(.*?)[*][*] Deck [*][*]%s", $file, $array);

If you don't want your result to contain Hand # and ** Deck **, an alternative to capturing would be lookarounds:

preg_match_all("%(?<=Hand #).*?(?=[*][*] Deck [*][*])%s", $file, $array);

If you do want them, you can simply remove the parentheses from the first pattern.

Upvotes: 3

Related Questions