phptext-parsing

Parse numeric string from right to left and isolate 1 to 3 separate values


I have a numeric string and I'd need to split it in groups of 2 starting from right, but not more than three groups.

To understand, the 3 groups are 'copper', 'silver' and 'gold' and the starting value is a synthetic money amount. For example:

10 -> 10 copper

1010 -> 10 silver and 10 copper

102030 -> 10 gold, 20 silver and 30 copper

1234567891010 -> 123456789 gold, 10 silver and 10 copper

How to do it in PHP?


Solution

  • I would just convert the String to an int like here and then do some arithmetical operations.

    Let x be the number

    r1 = x % 10000;
    gold = x / 10000;
    copper = r1 % 100;
    silver = r1 / 100;
    

    so you have all your information.

    Where % means modulo