phpregexmultiple-occurrence

How to use regex to get multiple occurrences of formula in PHP


I want to extract each arithmetic formula from this string:

+100*25-30

I used this regex:

preg_match_all("/(([\*\+\-\/])([0-9]+\.?[0-9]*))+/", "+100*25-30", $match);

It is capturing only last occurrence which is -30 but if I enter space before operator like this: +100 *25 -30, it is capturing all correctly, but I should do it without space. How to do it?


Solution

  • The (([\*\+\-\/])([0-9]+\.?[0-9]*))+ pattern is an example of a repeated capturing group. Since it matches the whole +100*25-30 string capturing each pair of the match operator with the number after it, only the last occurrence captured is stored in the Group 1 (that is -30).

    You can use

    preg_match_all("/([*+\/-]?)([0-9]+\.?[0-9]*)/", "+100*25-30", $match)
    

    See the PHP demo. Alternatively, preg_match_all("/([*+\/-]?)([0-9]*\.?[0-9]+)/", "+100*25-30", $match).

    See also the regex demo.

    Details: