匹配并解析文本中方括号占位符的内容

问题描述 投票:0回答:2

我有一个 PHP 变量 (

$content
),我需要在其中找到如下所示的特定模式:

[gallery::name/of/the/folder/]

我要搜索:

- starting with literal characters `[gallery::`
- any other character (variable length)
- ending with "]"

到目前为止,在 PHP 中我有:

preg_match('/\[gallery\:/', $content, $matches, PREG_OFFSET_CAPTURE);

我可以找到

[gallery:
,但仅此而已。

我希望能够找到其余的(

:name/of/the/folder/]
)。

php regex tags preg-match text-parsing
2个回答
50
投票

尝试捕捉它:

preg_match("/\[gallery::(.*?)]/", $content, $m);

现在

$m
是一个数组:

0 => [gallery::/name/of/the/folder/]
1 => /name/of/the/folder/

2
投票

将正则表达式更改为

'/\[gallery::([A-Za-z\/]+)\]/'

由于我将文件夹/路径部分放在括号中,因此您应该从中获得一个捕获组。

© www.soinside.com 2019 - 2024. All rights reserved.