0

I'm parsing some data and standardizing it for my website. The data I get from parsing:

[sizes] => Array
    (
        [0] => 5
        [1] => 6
        [2] => 10
        [3] => 6+
        [4] => 7
        [5] => 7+
        [6] => 8
        [7] => 8+
        [8] => 9
    )

I need to get:

[0] => US - 5
[1] => US - 6
[2] => US - 10
[3] => US - 6.5
[4] => US - 7.5
[5] => US - 8.5

I tried both preg_replace (all kind of different variations) and str_replace, but nothing seem to work. It seems like it overwrites values:

 $sizes[$i]= str_replace("7", "US - 7", $sizes[$i]); 
 $sizes[$i] = preg_replace('/\b6\b/', "US - 6", $sizes[$i]); 
 $sizes[$i] = preg_replace('~6\+$~m', "US - 6.5", $sizes[$i]); 
 $sizes[$i] = preg_replace('~5+$~m', "US - 5.5", $sizes[$i]);

I get back something like that:

        [0] => US - 10
        [1] => US - 5.US - 5
        [2] => US - 6
        [3] => US - 6.US - 5.US - 5
        [4] => US - 7
        [5] => US - 8
        [6] => US - 9
        [7] => US - US - 7.5
        [8] => US - US - 8.5

If anyone could help, I'd appreciate it. Thank you

Sanamarina
  • 25
  • 5

2 Answers2

0

Rather than trying to use regular expressions and assuming the constant 'US - x' and the a + means .5 size, then prefix with US - and just replace the + with .5 and use array_walk() to process each element...

$size = [0 => "5",
    1 => "6",
    2 => "10",
    3 => "6+",
    4 => "7",
    5 => "7+",
    6 => "8",
    7 => "8+",
    8 => "9"];

array_walk($size, function (&$data) { 
                $data = "US - ".str_replace("+", ".5", $data); 
});
print_r($size);

outputs...

Array
(
    [0] => US - 5
    [1] => US - 6
    [2] => US - 10
    [3] => US - 6.5
    [4] => US - 7
    [5] => US - 7.5
    [6] => US - 8
    [7] => US - 8.5
    [8] => US - 9
)

You could of course use any type of loop and not just array_walk(), the main logic is the same.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
0

Here is another approach:

<?php

$result = [];
$size = [
    0 => "5",
    1 => "6",
    2 => "10",
    3 => "6+",
    4 => "7",
    5 => "7+",
    6 => "8",
    7 => "8+",
    8 => "9"
];

foreach($size as $key => $value) {
    $result[$key] = "US - " . number_format(floatval($value), 2);
}

echo "<pre>";
print_r($result);
echo "</pre>";

Output:

Array
(
    [0] => US - 5.00
    [1] => US - 6.00
    [2] => US - 10.00
    [3] => US - 6.00
    [4] => US - 7.00
    [5] => US - 7.00
    [6] => US - 8.00
    [7] => US - 8.00
    [8] => US - 9.00
)