RegEx: Extended or

104 views Asked by At

I'm using RegEx to get specific parts of a file via PHP!

Let me show you an input-example:

=== KEYWORD1 ===
CONTENT

==== ANOTHERKEYWORD ====

CONTENT2

=== TESTKEYWORD ===

CONTENT3

My ReGex now might be: $pattern = "/.*=+ SEARCHTERM =+(.*?)=+.*=+.*/s";

SEARCHTERM is the flexible part of my regex.

Here an overview about what I expect to get and what I do receive:

  • When SEARCHTERM is replaced with KEYWORD1 I expect CONTENT but do get nothing
  • When SEARCHTERM is replaced with ANOTHERKEYWORD I expect CONTENT2and do get it (so this case works
  • When SEARCHTERM is replaced with TESTKEYWORD I expect CONTENT3 and get nothing

So the critical part is that there can be but don't has to be an empty line beyond the Searchterm AND that the RegEx first has to look if there is any other === ANYTHING === after SEARCHTERM and only if there is none, read everything 'till the files end.

I thought of $pattern = "/.*=+ SEARCHTERM =+(.*?)[=+.*=+.*|.*]/"; but this throws syntaxErrors.

Any help is very appreciated!

1

There are 1 answers

1
Toto On BEST ANSWER

Have a try with:

$str = <<<EOD
=== KEYWORD1 ===
CONTENT

==== ANOTHERKEYWORD ====

CONTENT2

=== TESTKEYWORD ===

CONTENT3    

EOD;

foreach(array('KEYWORD1', 'ANOTHERKEYWORD', 'TESTKEYWORD') as $keyword) {
    preg_match("/.*=+ $keyword =+([^=]+)/m", $str, $m);
    echo "$keyword -> $m[1]\n";;
}

output:

KEYWORD1 ->
CONTENT


ANOTHERKEYWORD ->

CONTENT2


TESTKEYWORD ->

CONTENT3