-3

Given the following string:

{start} SubPattern1 {end} 
....
{start} SubPattern2 {end}
....
{start} {start}SubPattern3{end} {end}

I need to find the regular expression that gives me the following result:

preg_match_all($regex, $string, $result);

print_r($result);

array(2
    0 => array(3
        0 => {start} SubPattern1 {end}
        1 => {start} SubPattern2 {end}
        2 => {start} {start}SubPattern3{end} {end}
    )
    1 => array(3
        0 => SubPattern1 
        1 => SubPattern2 
        2 => {start}SubPattern3{end} 
    )
)

Thank you!

Edit

For visual purpose I wrote a multiline string. But I need that the expression works even if all the text is in a single line string. eg:

{start}SubPattern1{end}{start}SubPattern2{end}{start}{start}SubPattern3{end}{end}

Jorge Luis
  • 17
  • 6

2 Answers2

0

You can use this

^{start}(.*){end}$
  • ^ - Start of string.
  • {start} - Matches {start}.
  • (.*) - Matches anything except new line. (capturing group).
  • {end} - Matches {end}.
  • $ - End of the string.

Demo

Code Maniac
  • 33,907
  • 4
  • 28
  • 50
0

You could match {start} and {end} and use a capturing group and use recursion for the pattern:

{start}((?:(?:(?!{(?:start|end)}).)+|(?R))*){end}

For example:

$string = <<<DATA
{start} SubPattern1 {end} 
{start} SubPattern2 {end}
{start} {start}SubPattern3{end} {end}
DATA;

preg_match_all('/{start}((?:(?:(?!{(?:start|end)}).)+|(?R))*){end}/', $string, $result);
print_r($result);

Explanation

  • {start} Match literally
  • ( Start capturing group
    • (?: Non capturing group
      • (?: Non capturing group
        • (?!{(?:start|end)}). Negative lookahead to assert what is on the right is not {start} or {end}. If that is the case, match any character.
      • )+|(?R) Close non capturing group and repeat 1+ times or | recurses the entire pattern
    • )* Close non capturing group and repeat 0+ times
  • ) Close capturing group
  • {end} - Match literally

Regex demo

Result:

Array
(
    [0] => Array
        (
            [0] => {start} SubPattern1 {end}
            [1] => {start} SubPattern2 {end}
            [2] => {start} {start}SubPattern3{end} {end}
        )

    [1] => Array
        (
            [0] =>  SubPattern1 
            [1] =>  SubPattern2 
            [2] =>  {start}SubPattern3{end} 
        )

)

Php demo

The fourth bird
  • 96,715
  • 14
  • 35
  • 52