Capture groups of comma separate digits and floating point values enclosed in parentheses

Viewed 41

The goal is to capture 3 groups of values separated by commas enclosed in parentheses.

The string to be parsed:-

(8x10x2cm, 0.2kg, 596010 SKU)

At a minimum, there would be 3 named capture groups dimensions, weight and sku

The specified unit cm and kg and keyword SKU does not need to be considered and should not be captured.

Ideally the dimesion capture group would split on x to give additional named capture groups width, height and depth

Floating point values such as 0.2 in weight also needs to be considered in dimensions e.g. 8.5x10.5x2cm for capture

width = 8 height = 10 depth = 2 weight = 0.2 sku = 596010

Note sku is not always numeric but always appears before the string SKU e.g. possible sku values include C798015, 596001B, 572920B10, 741150.1

2 Answers

Use the regex:

\((?<width>\d+(?:\.\d+)?)x(?<height>\d+(?:\.\d+)?)x(?<depth>\d+(?:\.\d+)?)cm,\s*(?<weight>\d+(?:\.\d+)?)kg,\s*(?<sku>.*)\s*SKU\)

See the regex demo which matches all your sample inputs.

Here is a solution using preg_match_all followed by flattening the output 2D array:

$input = "(8x10x2cm, 0.2kg, 596010 SKU)";
preg_match_all("/\b(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)cm, (\d+(?:\.\d+)?)kg, (\d+(?:\.\d+)?)(?: SKU)?\)/", $input, $matches);
$output = [];
for ($i=1; $i < count($matches); $i++){
    $output[$i - 1] = $matches[$i][0];
}

print_r($output);

This prints:

Array
(
    [0] => 8
    [1] => 10
    [2] => 2
    [3] => 0.2
    [4] => 596010
)

I didn't name the capture groups, but then again you don't need that to make use of the above answer, as the order of capture groups is guaranteed by the regex pattern being used.

Related