PHP: preg_match_all, which first matches the internal brackets?

In PHP, I have a line with parentheses enclosed:

bar[foo[test[abc][def]]bar]foo 

I need a regular expression that matches the parentheses first, so the order in which preg_match_all finds matching parenthesis pairs should be:

 [abc] [def] [test[abc][def]] [foo[test[abc][def]]bar] 

All texts may vary.

Is this possible with preg_match_all ?

+2
source share
2 answers

This is not possible with regular expressions. No matter how complicated your regular expression is, it will always return the very first match in the first place.

At best, you will have to use a few regular expressions, but even then you will have problems because regular expressions cannot count the matching brackets. It is best to parse this line in a different way.

+2
source

In your question, you don’t see which “match structure” you want ... But you can only use simple arrays. Try

  preg_match_all('#\[([az\)\(]+?)\]#',$original,$m); 

that for $original = 'bar[foo[test[abc][def]]bar]foo' returns an array with "abc" and "def", internal.


For your output, you need a loop for the “parsing task”. PCRE with preg_replace_callback is better for parsing.

Perhaps this cycle is a good key to your problem,

  $original = 'bar[foo[test[abc][def]]bar]foo'; for( $aux=$oldAux=$original; $oldAux!=($aux=printInnerBracket($aux)); $oldAux=$aux ); print "\n-- $aux"; function printInnerBracket($s) { return preg_replace_callback( '#\[([az\)\(]+?)\]#', // the only one regular expression function($m) { print "\n$m[0]"; return "($m[1])"; }, $s ); } 

Result (callback):

 [abc] [def] [test(abc)(def)] [foo(test(abc)(def))bar] -- bar(foo(test(abc)(def))bar)foo 

See also this related question .

0
source

Source: https://habr.com/ru/post/898056/


All Articles