views:

71

answers:

2
text text text
text text text

{test}
    content
    content
    content
{/test}

text text text
text text text

i need to get two separate results from the above string:
1.

{test}
    content
    content
    content
{/test}

2.

    content
    content
    content

so, what should be the two separate regular expression patterns for PHP to get the above two results

+1  A: 

To capture the tags and contents together:

/(\{test\}[^\x00]*?\{\/test\})/

To capture just the contents:

/\{test\}([^\x00]*?)\{\/test\}/
Asaph
+2  A: 

What about something like this :

$str = <<<STR
text text text
text text text

{test}
    content
    content
    content
{/test}

text text text
text text text
STR;

$m = array();
if (preg_match('#\{([a-zA-Z]+)\}(.*?)\{/\1\}#ism', $str, $m)) {
    var_dump($m);
}

Which will get this kind of output :

array
  0 => string '{test}
    content
    content
    content
{/test}' (length=50)
  1 => string 'test' (length=4)
  2 => string '
    content
    content
    content
' (length=37)

So, in $m[0] you have the whole matched string (ie tags+content), and in $m[2] you only have to content between the tags.

Note I have used "generic" tags, and not specifically "test" ; you can change that if you'll only have "test" tags.

For more informations, you can take a look at, at least :

Pascal MARTIN
oh, sorry, i used [.*?] instead of (.*?) and that was my fault! however, thanks for your nice reply!would you please explain me the term {/\1}
Saiful
The \1 is a "back reference" to the first pattern that was matched ; the idea here is that the closing tag should correspond to the opening tag ;; for more informations, you can read : http://www.php.net/manual/en/regexp.reference.back-references.php
Pascal MARTIN