正则表达式匹配花括号内的所有内容

时间:2013-08-15 14:41:11

标签: php regex

我有这个PHP代码,我想匹配花括号内的所有内容{}

$sentence= "This {is|or|and} a {cat|dog|horse} for a {kid|men|women}";
preg_match("/\{.*?\}/", $sentence, $result);
print_r($result);

但我只得到这个输出:

Array ( [0] => {is|or|and} ) 

但我需要的是这样的结果:

Array ( [0] => is|or|and
[1] => cat|dog|horse
[2] => kid|men|women
 ) 

我应该使用什么正则表达式?

5 个答案:

答案 0 :(得分:10)

使用preg_match_all代替吗?

preg_match_all("/\{.*?\}/", $sentence, $result);

如果你不想要大括号,你可以做两件事:

捕获大括号内的部分并使用$result[1]将其恢复,就像正确建议的HamZa一样:

preg_match_all("/\{(.*?)\}/", $sentence, $result);
print_r($result[1]);

或使用外观(但它们可能有点难以理解):

preg_match_all("/(?<=\{).*?(?=\})/", $sentence, $result);
print_r($result[0]);

请注意,您也可以使用[^}]*代替.*?,这通常被认为更安全。

答案 1 :(得分:3)

要获得所有结果,请使用preg_match_all

improve performance,请使用[^}]*代替.*?

要摆脱大括号,你可以

  1. \{([^}]*)\}等内容进行分组,并从$matches[1]获取结果
  2. 排除带有外观的大括号,例如(?<=\{)[^}]*(?=\})
  3. 使用\K排除第一个大括号,使用\{\K[^}]*(?=\})
  4. 等前瞻排除第二个大括号

答案 2 :(得分:2)

您需要使用preg_match_all,是的,但您还需要将正则表达式修改为\{(.*?)\}See this Regex101 for proof。在你的原始正则表达式中,你没有对结果进行分组,从而得到括号。

答案 3 :(得分:1)

使用preg_match_all

$sentence= "This {is|or|and} a {cat|dog|horse} for a {kid|men|women}";
preg_match_all("/\{[^}]+}/", $sentence, $result);
print_r($result[0]);

会给你

Array
    (
        [0] => {is|or|and}
        [1] => {cat|dog|horse}
        [2] => {kid|men|women}
    )

答案 4 :(得分:1)

将您的preg_match更改为preg_match_all$result更改为$result[1]并稍微修改正则表达式,如下所示:

<?php
$sentence= "This {is|or|and} a {cat|dog|horse} for a {kid|men|women}";
preg_match_all("/\{(.*?)\}/", $sentence, $result);
print_r($result[1]);
?>

输出:

Array
(
    [0] => is|or|and
    [1] => cat|dog|horse
    [2] => kid|men|women
)
相关问题