【发布时间】:2020-08-10 16:34:13
【问题描述】:
我有以下字符串,其中包含与preg_match 匹配的可选括号。键是输入,值是预期的输出:
$strings = [
'(prefix) (string in parens)' => 'string in parens',
'(prefix) string not in parens' => 'string not in parens',
'(prefix) parens (at the end)' => 'parens (at the end)',
];
假设我想在单个 preg_match 中执行此操作,我目前有以下内容:
preg_match('/^\(prefix\) (\((.+)\)|.+)$/', $input, $matches);
$output = (isset($matches[2]) ? $matches[2] : $matches[1]);
这可行,但需要一个单独的子模式来检测所看到的格式。有没有更好的方法在单个子模式中做到这一点?在子模式的任一端假设可选括号是不够的,因为我可能想包含括号。
我知道我还有其他选项,例如分别去除前缀和括号,但我想知道是否有更好的方法来做到这一点而无需先改变逻辑。
【问题讨论】:
标签: php regex preg-match