I have values for the dimensions of the product the data of product is added via admin panel using import feature there are lots of products so doing it manually is a headache so on the front end if the value in 0 and space for any of the dimension values, then have to exclude it without the value at all. Ex. if the value is 1 x 1 x 0 (L X W X H) or 1 x 1 x (L X W X H), then record the value on the site as 1 x 1 (L X W). I have tried here is the values in the table
Size : 9.06 x 5.12 x 0 (LxWxH)
I have tried using str_replace function but the problem is that how will i gonna remove the symbol of the relatable value it could be 1 x 0 x 1 (L X W X H) so it should be like this 1 x 1 (L X H)
`$ship_weight_attr = $ship_weight_values[$size_pos];
$ship_weight_attr = str_replace(' x 0', '', $ship_weight_attr);
$ship_weight_attr = str_replace(' x ', '', $ship_weight_attr);
`
Now I am looking to get a better solution so I can get rid of the unusual values
CodePudding user response:
This what you need? It's probably longer than it needs to be but easy to understand.
function formatDimensions($value) {
$aDimensions = explode('x', $value);
$aDescription = [];
$aValue = [];
if (($aDimensions[0] ?? 0) > 0) {
$aDescription[] = 'L';
$aValue[] = trim($aDimensions[0]);
}
if (($aDimensions[1] ?? 0) > 0) {
$aDescription[] = 'W';
$aValue[] = trim($aDimensions[1]);
}
if (($aDimensions[2] ?? 0) > 0) {
$aDescription[] = 'H';
$aValue[] = trim($aDimensions[2]);
}
$description = join(' x ', $aDescription);
$value = join(' x ', $aValue);
return $value . ' (' . $description . ')';
} //funct
echo formatDimensions('1 x 1 x 0');
echo '<br>';
echo formatDimensions('1 x 2 x ');
echo '<br>';
echo formatDimensions('1 x 3 x 4');
This outputs:
1 x 1 (L x W)
1 x 2 (L x W)
1 x 3 x 4 (L x W x H)
CodePudding user response:
Here's a regex solution that will handle any order:
<?php
function process($s)
{
$exp = "/([\d.]*)\s*[xX]\s*([\d.]*)\s*[xX]\s*([\d.]*)\s*\(([LWH])[xX]([LWH])[xX]([LWH])\)/";
preg_match( $exp, $s, $matches );
print_r($matches);
$one = array();
$two = array();
for( $i = 0; $i < 3; $i )
{
if( $matches[$i 1] != 0 )
{
$one[] = $matches[$i 1];
$two[] = $matches[$i 4];
}
}
return implode(" x ",$one) . " (" . implode("X",$two) . ")";
}
echo process("9.06 x 5.12 x 0 (LxWxH)");
?>
Output:
Array
(
[0] => 9.06 x 5.12 x 0 (LxWxH)
[1] => 9.06
[2] => 5.12
[3] => 0
[4] => L
[5] => W
[6] => H
)
9.06 x 5.12 (LXW)