Question

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!

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top