获取以特定字符串开头且位于括号之间的文本中的所有匹配项
Get all matches in text which start with specific string and is between parentheses
所以我在这里找到了可在括号之间查找文本的正则表达式:
preg_match_all('/\(((?:[^\(\)]++|(?R))*)\)/', $string, $matches)
这很好用。问题是当我添加我想开始的文本时:preg_match_all('/(text)\(((?:[^\(\)]++|(?R))*)\)/', $string, $matches)
那么它只适用于这样的字符串:
text(some text between parentheses and starting with "text")
但我也需要它来处理这样的字符串:
text(some text between parentheses (more text between parentheses) and starting with "text")
据我所知,问题出在这部分 (?R)(递归),但我不确定如何更改此正则表达式以使用我想要的字符串。
您可以将正则表达式更改为:
$re = '/text ( \( (?: [^()]* | (?-1) )* \) )/x';
第 1 组中有括号内的文字。
PCRE 中的 (?-1)
是先前编号的捕获组的反向引用。
更新:
根据下面的评论,OP 希望捕获括号之间的文本但不捕获括号。这个正则表达式应该有效:
$re = '/text ( \( ( (?: [^()]* | (?-2) )* ) \) )/x';
检查捕获的第 2 组中括号内的文本。
所以我在这里找到了可在括号之间查找文本的正则表达式:
preg_match_all('/\(((?:[^\(\)]++|(?R))*)\)/', $string, $matches)
这很好用。问题是当我添加我想开始的文本时:preg_match_all('/(text)\(((?:[^\(\)]++|(?R))*)\)/', $string, $matches)
那么它只适用于这样的字符串:
text(some text between parentheses and starting with "text")
但我也需要它来处理这样的字符串:
text(some text between parentheses (more text between parentheses) and starting with "text")
据我所知,问题出在这部分 (?R)(递归),但我不确定如何更改此正则表达式以使用我想要的字符串。
您可以将正则表达式更改为:
$re = '/text ( \( (?: [^()]* | (?-1) )* \) )/x';
第 1 组中有括号内的文字。
PCRE 中的(?-1)
是先前编号的捕获组的反向引用。
更新:
根据下面的评论,OP 希望捕获括号之间的文本但不捕获括号。这个正则表达式应该有效:
$re = '/text ( \( ( (?: [^()]* | (?-2) )* ) \) )/x';
检查捕获的第 2 组中括号内的文本。