PHP: find statement in regex expression

I currently have the following situation: I try to parse text looking for placeholders (their designation is "{...}"), and then I will replace them with actual text.

I was thinking about regular expressions

$foo = "Hello World {foo{bar}} World Hello!"; $bar = array(); preg_match_all('@\{.+\}@U', $foo, $bar); var_dump($bar); 

But it returns

 array(1) { [0]=> array(1) { [0]=> string(9) "{foo{bar}" } } 

Due to the fact that he will be greedy, he will:

 array(1) { [0]=> array(1) { [0]=> string(10) "{foo{bar}}" } } 

But I want the result to be something like this:

 array(1) { [0]=> array(2) { [0]=> string(5) "{bar}" [1]=> string(10) "{foo{bar}}" } } 

Is there a way to achieve this with preg_match (_all) and regular expressions?

Or do I need to iterate over the string $ bar again and again until there are no subqueries left in the result set?

+4
source share
1 answer

You are lucky to have PCRE. This needs to be solved using recursion: http://regex101.com/r/pO3hA0

/(?=({(?>[^{}]|(?1))+}))/g (you don't need the g flag in php)

+3
source

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


All Articles