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
My Answer:
Here is a PHP code snippet that achieves the desired result:
php
$string = "(8x10x2cm, 0.2kg, 596010 SKU)";
$pattern = '/\(([\d.]+)x([\d.]+)x([\d.]+)cm, ([\d.]+)kg, (\d+ [A-Za-z]+)\)/';
preg_match($pattern, $string, $matches);
$width = $matches[1];
$height = $matches[2];
$depth = $matches[3];
$weight = $matches[4];
$sku = $matches[5];
echo "Width: $width\n";
echo "Height: $height\n";
echo "Depth: $depth\n";
echo "Weight: $weight\n";
echo "SKU: $sku\n";
?>
This code snippet uses a regular expression pattern to capture the desired groups of values from the input string. The named capture groups are width, height, depth, weight, and sku. The values are then extracted from the matches array and printed out.
Rate this post
4 of 5 based on 2597 votesComments