A.N.M. Saiful Islam
A.N.M. Saiful Islam

Reputation: 2138

PHP RegularExpression : match anything (including whitespaces)

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

Upvotes: 0

Views: 461

Answers (2)

Pascal MARTIN
Pascal MARTIN

Reputation: 401002

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 :

Upvotes: 3

Asaph
Asaph

Reputation: 162801

To capture the tags and contents together:

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

To capture just the contents:

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

Upvotes: 1

Related Questions