【发布时间】:2017-12-03 21:02:44
【问题描述】:
我想用 preg_match_all 解析这个字符串:
$str = "form.input|type()
form.input|type('text')
form.input|type('text', {'width': '100px', 'height': '50px'})
form.input|type('image', {'path': '/path/to/image'})";
preg_match_all('/form\.input\|type\((?:(.*))?\)/', $str, $matches);
预期输出:
[0] => Array
(
[0] => form.input|type()
[1] => form.input|type('text')
[2] => form.input|type('image', {'path': '/path/to/image'})
[3] => form.input|type('text', {'width': '100px', 'height': '50px'})
)
[1] => Array
(
[0] =>
[1] => text
[2] => image
[3] => text
)
[2] => Array
(
[0] =>
[1] =>
[2] => {'path': '/path/to/image'}
[3] => {'width': '100px', 'height': '50px'}
)
实际输出:
Array
(
[0] => Array
(
[0] => form.input|type()
[1] => form.input|type('text')
[2] => form.input|type('image', {'path': '/path/to/image'})
[3] => form.input|type('text', {'width': '100px', 'height': '50px'})
)
[1] => Array
(
[0] =>
[1] => 'text'
[2] => 'image', {'path': '/path/to/image'}
[3] => 'text', {'width': '100px', 'height': '50px'}
)
)
这个模式可以解析案例:
form.input|type()
form.input|type('text')
我尝试通过这种模式进行匹配:
/form\.input\|type\((?:(.*)(?:,(.*))?)?\)/
但由于子非捕获组,无法匹配模式。
我使用非捕获组(?:(.*))? 进行可选匹配,但只有在没有使用第一个模式的子非捕获组时才能匹配。
我试图搜索这种情况下的匹配,但我找不到正确的答案。
【问题讨论】:
-
你期望输出什么?您的模式匹配上述所有情况:regex101.com/r/JLmX3Q/1 甚至
\Qform.input|type(\E(?:([^()]*))?\) -
@Jan 我用预期的输出编辑了这个问题。此模式将 type() 中的所有内容匹配为一个字符串。但我想将它们分成两部分进行匹配:字符串类型和 json 选项。
-
了解您不想匹配的内容会很有帮助。从您的示例来看,这已经足够了
/f.+/ -
@miknik 你能在例子中应用它吗? /form\.input\|type((?:(.*))?)/
-
@semsem 您的问题是“我想使用 preg_match 解析这个字符串”这对我来说有点不清楚。您是否使用
preg_match_all()从每一行中提取值?或者这实际上是四个单独的示例字符串,您想在所有四个上调用preg_match()?请将您的 php 实现添加到问题中以阐明实际任务?您想每次返回 2 个捕获组吗?即使其中一个或两个捕获组为空?这些都是必须包含在您的问题中的关键细节。
标签: php regex preg-match-all