Angga Ari Wijaya
Angga Ari Wijaya

Reputation: 1811

How to format some numbers in a string in PHP?

I have string :

HAMMER FORGED (5.400PCE-2,340Kg-6.000M3-DANGER TYPE 2)

and want format that string to

HAMMER FORGED (5,40PCE-2.340,00Kg-6M3-DANGER TYPE 2)

Each number I know I can use number_format(), but how to extract those numbers and put it back to the right place?

The pattern is fixed: goods name (alpha num) following by attributes ([qty][unit]-[weight]Kg-[volume]M3-type), lenght of character dynamic

Upvotes: 1

Views: 141

Answers (1)

mickmackusa
mickmackusa

Reputation: 47894

Here is one solution with preg_replace_callback(). It's a bit convoluted because you need to also capture the substrings between your float values.

the digital matches are:

  1. stripped of commas (where necessary)
  2. converted to float values
  3. reformatted by number_float() (as desired)

Code: (Demo)

$string = 'HAMMER FORGED (5.400PCE-2,340Kg-6.000M3-DANGER TYPE 2)';

echo preg_replace_callback(
    '~\(([\d.]+)([A-Z]+-)([\d,.]+)(Kg-)([\d.]+)~',
    function($m) {
        return 
            "(".
            number_format((float)$m[1], 2, ",", ".").
            "$m[2]".
            number_format((float)str_replace(",", "", $m[3]), 2, ",", ".").
            "$m[4]".
            number_format((float)$m[5], 0);
    },
    $string);

Output:

HAMMER FORGED (5,40PCE-2.340,00Kg-6M3-DANGER TYPE 2)

Pattern Demo

Here are the matches that relate to the $m array that preg_replace_callback() generates:

Full match  14-37   `(5.400PCE-2,340Kg-6.000`
Group 1.    15-20   `5.400`
Group 2.    20-24   `PCE-`
Group 3.    24-29   `2,340`
Group 4.    29-32   `Kg-`
Group 5.    32-37   `6.000`

Upvotes: 1

Related Questions