我有这个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
)
我应该使用什么正则表达式?
是否改用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]);
请注意,您也可以使用[^}]*
而不是.*?
,这通常被认为更安全。
要获得所有结果,请使用preg_match_all
。
要提高性能,请使用[^}]*
而不是.*?
。
要去掉牙套,你可以
-
对
'{([^}]*)'}
等内容进行分组,并从$matches[1]
中获得结果 -
或使用查找排除大括号,如
(?<='{)[^}]*(?='})
-
或排除具有
'K
的第一个大括号和具有类似'{'K[^}]*(?='})
的前瞻性的第二个大括号
您需要使用preg_match_all
,是的,但您也需要将Regex修改为'{(.*?)'}
。请参阅此Regex101以获取证据。在最初的Regex中,您没有对结果进行分组,因此也得到了括号。
使用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}
)
将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
)