PHP正则表达式:匹配任何东西(包括空格)

时间:2009-12-09 05:37:44

标签: php pattern-matching preg-match preg-match-all

text text text
text text text

{test}
    content
    content
    content
{/test}

text text text
text text text

我需要从上面的字符串中得到两个单独的结果:
1。

{test}
    content
    content
    content
{/test}

2

    content
    content
    content

那么, PHP 的两个单独的正则表达式应该是什么才能获得上述两个结果

2 个答案:

答案 0 :(得分:3)

这样的事情:

$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);
}

将获得此类输出:

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

因此,在$m[0]中,您拥有完整匹配的字符串(即标记+内容),而在$m[2]中,您只需要在标记之间添加内容。

注意我使用过“通用”标签,而不是“test”;如果您只有“test”代码,则可以更改。

有关更多信息,您至少可以看一下:

答案 1 :(得分:1)

一起捕捉标签和内容:

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

仅捕获内容:

/\{test\}([^\x00]*?)\{\/test\}/
相关问题