【发布时间】:2015-10-05 17:16:50
【问题描述】:
我有以下文字
$text = 'This is a test to see if something(try_(this(once))) works';
我需要从文本中获取带有正则表达式的something(try_(this(once)))。我有以下问题
-
我的嵌套不会保持不变,我的文本可以是
-
something(try_(this(once)))或 -
something(try_this(once))或 something(try_thisonce)
-
我已经尝试了在整个网站上找到的许多正则表达式,但无法使其正常工作。这是我最近的一次
示例 1:
$text = 'This is a test to see if something(try_(this(once))) works';
$output = preg_match_all('/(\(([^()]|(?R))*\))/', $text, $out);
?><pre><?php var_dump($out[0]); ?></pre><?php
这个输出
array(1) {
[0]=>
string(18) "(try_(this(once)))"
}
无论我在哪里添加单词something(例如'/something(\(([^()]|(?R))*\))/' 和'/(\something(([^()]|(?R))*\))/'),我都会得到一个空数组或NULL
示例 2
$text2 = 'This is a test to see if something(try_(this(once))) works';
$output2 = preg_match_all('/something\((.*?)\)/', $text2, $out2);
?><pre><?php var_dump($out2[0]); ?></pre><?php
有了这段代码,我确实得到了something这个词,
array(1) {
[0]=>
string(25) "something(try_(this(once)"
}
但随后表达式停止并在第一次关闭 ) 后返回,这是预期的,因为这不是递归表达式
如何在第一个开头 ( 之前递归匹配并返回带有单词 something 的嵌套括号,如果可能的话,那么在单词 something 之前可能会有也可能没有空格,因为例子
-
something(try_(this(once)))或 -
something (try_(this(once)))
【问题讨论】:
-
你为什么不能这样做? regex101.com/r/jW9iW0/1
-
@dustmouse 它同样适用于
something(try_(this(once))),但something (try_(this(once)))什么也不返回。任何想法如何在可能发生或可能不发生的情况下匹配空格,请将其发布为答案,以便我给您一些信用 -
好的,我发布了一个可以处理空格的答案。