Search code examples
regexpreg-matchpreg-match-all

Part of match in match. How to find all?


I'm looking for all variables in document and spot undesirable feature. During:

$from = "(some txt)$aaa$bbb(another txt)";
preg_match_all("/[\$]([a-zA-Z_]{1})([a-zA-Z0-9_]*?)(\W)/", $from, $matches);

script return only $aaa as a match but not $bbb. I have no idea how to work it out. Please help :)


Solution

  • That's because of the none word token at the end of your regex which makes your regex match $aaa$ (the \W match the last $). For refuse of such behavior you can put the \W in a positive look ahead.Also you can put all the regex between $ and \W in one group :

    /\$([a-zA-Z_][a-zA-Z0-9_]*)(?=\W)/
    

    See demo https://regex101.com/r/uV1cA2/1