我有以下文本
$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)))
something(try_(this(once))
), 它同样有效,但是something (try_(this(once)))
返回空值。如果有任何想法可以匹配可能出现或不出现的空格,请将其作为答案发布,以便我可以给您一些信用。 - Pieter Goosen