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 得到上述两个结果

有帮助吗?

解决方案

什么事情是这样的:

$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"标签。

欲了解更多信息,你可以看一看,至少:

其他提示

要捕获标签和内容一起:

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

要捕捉只是内容:

/\{test\}([^\x00]*?)\{\/test\}/
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top