Page 1 of 1

regex for physical measurments

Posted: Tue Oct 28, 2008 8:25 pm
by vinci91
I need a regex to match physical measurments.
I am importing a CSV file which contains measurements. The client writes these measurements in several formats...
eg:

569 - doesnt have unit, so need to append 'mm' by default. = 569mm
569" - has inches unit, so dont append 'mm'. = 569"
567+45 - has a double measurement, so need to recognise this as a number including the '+' and append 'mm'. = 567+45mm
567"+56" - double measurement with inches, dont append. = 567"+56"
567+56" - double measurement with inches, dont append (assume both are inches). = 567+56"
45Kg - already has unit, so dont append 'mm'. = 45Kg

Ive tried several ways: where csv[$i] is the current value... and assuming csv[$i] != '';

Code: Select all

 
 
if ($csv[$i] != '') {
  //get the measurement (match numbers and + sign only)
  if (preg_match('/\d+\+/', $csv[$i], $num_match)) {
    $measurement = $num_match[0]
  } else {
    //client must have entered the unit without a meaurement
  }
 
  //get the unit (match any letter or special character, except plus sign)
  if (preg_match('/\D+\W+[^\+]/', $csv[$i], $unit_match) ) {
    $unit = $unit_match[0];
  } else {
     $unit = 'mm';
  }
}
 
$csv[$i] = $measurement.$unit;
 
 
Doesnt seem to be working, as 'mm' is appended to everything, and overwrites m,cm,g,Kg," and '

Re: regex for physical measurments

Posted: Wed Oct 29, 2008 1:21 am
by GeertDD
I think this one could be easier than you think. Studying your examples, the only thing that you need to check for is the last character. If it is a digit, append "mm"; if it is anything else, don't append anything.

Code: Select all

$csv = '569,569",567+45,567"+56",567+56",45Kg';
$csv = explode(',', $csv);
 
foreach ($csv as $value)
{
    $new_value = preg_replace('~(?<=\d)$~', 'mm', $value);
    echo $value, ' --> ', $new_value, "\n";
}

Re: regex for physical measurments

Posted: Thu Oct 30, 2008 6:41 am
by vinci91
Thanks!
- youre right - that is a simpler way of doing things...
I'll give it a try
v