Q:

preg_match_all split conditional expression with special caracteres

I have data in this format:
Randomtext1(#random2#, #random4#) == 1 && Randomtext2 (ran dom) != 2 || #Randomtext3# > 3 && Randomtext4 (random5,random7,random8) || Randomtext5  (Randomtext4 (random5,random7,random8), random10) < Randomtext11()

with this:
preg_match_all("~\w+(?:\s*(\([^()]*+(?:(?1)[^()]*)*+\)))?~", $expression, $matches);

I obtain:
0 => 'Randomtext1(#random2#, #random4#)',
1 => '1',
2 => 'Randomtext2 (ran dom)',
3 => '2',
4 => 'Randomtext3',
5 => '3',
6 => 'Randomtext4 (random5,random7,random8)',
7 => 'Randomtext5  (Randomtext4 (random5,random7,random8), random10)',
8 => 'Randomtext11()',

But i want:
0 => 'Randomtext1(#random2#, #random4#)'
1 => '1'
2 => 'Randomtext2 (ran dom)'
3 => '2'
4 => '#Randomtext3#'
5 => '3',
6 => 'Randomtext4 (random5,random7,random8)',
7 => 'Randomtext5  (Randomtext4 (random5,random7,random8), random10)',
8 => 'Randomtext11()',

My problem, i lost # off element 4
Any ideas?

A:

The \w is 0-9a-zA-Z_* you need to allow the # as well, you can use an alteration or a character class.
[#\w]+

or
(?:#|\w)+

Full example:
[#\w]+(?:\s*(\([^()]*+(?:(?1)[^()]*)*+\)))?

Demo: https://3v4l.org/75eGQ
Regex demo: https://regex101.com/r/1PYvpO/1/

\w stands for "word character". It always matches the ASCII characters [A-Za-z0-9_]. Notice the inclusion of the underscore and digits. In most flavors that support Unicode, \w includes many characters from other scripts. There is a lot of inconsistency about which characters are actually included. Letters and digits from alphabetic scripts and ideographs are generally included. Connector punctuation other than the underscore and numeric symbols that aren't digits may or may not be included. XML Schema and XPath even include all symbols in \w. 

*https://www.regular-expressions.info/shorthand.html

