PHP: regex match full matching parentheses?
In PHP I have the following line:
$text = "test 1
{blabla:database{test}}
{blabla:testing}
{option:first{A}.Value}{blabla}{option:second{B}.Value}
{option:third{C}.Value}{option:fourth{D}}
{option:fifth}
test 2
";
I need to get all { option
...} from this line (total 5 on this line). Some of them have multiple nested parentheses and some don't. Some of them are on the same line, some are not.
I already found this regex:
(\{(?>[^{}]+|(?1))*\})
so the following works great:
preg_match_all('/(\{(?>[^{}]+|(?1))*\})/imsx', $text, $matches);
Text that is not inside the curly braces is filtered out, but matches also include items blabla
that I don't need.
Is it possible to change this regex with just option
-items?
source to share
I have changed your initial expression to find the string '(option :)' appended with non-whitespace characters (\ S *) delimited by curly braces '{}'.
\{(option:)\S*\}
Given your input text, the following entries are matched in regexpal:
test 1
{blab: database {trial}}
{blab: testing}
{option: first {A} .Value} {option: second {B} .Value}
{option: third {C} .Value}
{option: fourth {D}}
{option: fifth}
test 2
source to share
This problem is much better for a proper parser, however you can do it with a regex if you really want to.
This should work as long as you don't nest options inside other parameters.
preg_match_all(
'/{option:((?:(?!{option:).)*)}/',
$text,
$matches,
PREG_SET_ORDER
);
Short description.
{option: // literal "{option:"
( // begin capturing group
(?: // don't capture the next bit
(?!{option:). // everything NOT literal "{option:"
)* // zero or more times
) // end capture group
} // literal closing brace
var_dump
The output from ed with your example input looks like this:
array(5) {
[0]=>
array(2) {
[0]=>
string(23) "{option:first{A}.Value}"
[1]=>
string(14) "first{A}.Value"
}
[1]=>
array(2) {
[0]=>
string(24) "{option:second{B}.Value}"
[1]=>
string(15) "second{B}.Value"
}
[2]=>
array(2) {
[0]=>
string(23) "{option:third{C}.Value}"
[1]=>
string(14) "third{C}.Value"
}
[3]=>
array(2) {
[0]=>
string(18) "{option:fourth{D}}"
[1]=>
string(9) "fourth{D}"
}
[4]=>
array(2) {
[0]=>
string(14) "{option:fifth}"
[1]=>
string(5) "fifth"
}
}
source to share