0

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?

the_nutria
  • 75
  • 5

2 Answers2

5

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

Jelmer
  • 2,663
  • 2
  • 27
  • 45
Alex VII
  • 930
  • 6
  • 25
  • oh yes that is much simpler than splitting the string! I didn't get that % thing but I've used a floor() to truncate decimal values. thank you – the_nutria Dec 24 '12 at 15:18
  • % means modulo, so for example 5 % 2 is 3, so 3 ist the rest if you devide 5 by 2. Another example is: 1002 % 10 is 2, so 1002 = 100 * 10 + 2 – Alex VII Dec 24 '12 at 15:21
  • @the_nutria Here are the docs: http://php.net/manual/en/language.operators.arithmetic.php – Jelmer Dec 24 '12 at 15:23
  • @the_nutria % is the modulo operator. Basically, you're dividing something by another number, and instead of returning the result, you return the remainder. ie 100/13 = 7.69, so 100 % 13 would return 100 - (13 * 7) = 100 - 91 = 9 – Michael Dec 24 '12 at 15:23
0

Using a regular expression:

$items = array('12', '1234', '123456', '1234567891234');

foreach ($items as $item)
{
    echo $item;

    preg_match('/^(?:(?<gold>\d*)(?<silver>\d\d))?(?<copper>\d\d)$/', $item, $result);

    foreach ($result as $key => $value)
    {
        if (is_int($key))
        {
            unset($result[$key]);
        }
    }
    var_dump($result);
}
Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52