# Weight unit to raw value converter?

Hello,

For a study I’m making a need a script that can convert people’s height and weight to a standard value (and back, but I could probably do the ‘back’ one myself, so it’s not important).

For example, somebody could enter 5’ 8" and it will automatically convert to centimeters and entered in the database. Same goes for weight (50kgs, 130lbs, etc)

Does anyone know a reliable script for this?

Thank you,
Peter

Just write your own. Use a regular expression to match the numbers, do the simple maths and output the correct value.

``````preg_match('/^(\\d+)\\' ?(\\d+)"\$/', \$input, \$matches);
\$height = \$matches[1] * 12 + \$matches[2]; // height in inches
// now convert it to cm

\$unit = substr(\$input, -2);
if (\$unit === 'lb')
\$weight = (int)\$input / 2.2;
elseif (\$unit === 'kg')
\$weight = (int)\$input * 2.2
``````

It should be “kg” or “lb”, not with an “s” on the end, hence I used substr(\$input, -2). If you might expect both, then you’d best use a regular expression:

``````preg_match('/^(\\d+) ?(kg|lb)s?\$/', \$input, \$matches);
if (\$matches[2] === 'lb') \$weight = (int)\$matches[1] / 2.2;
elseif (\$matches[2] === 'kg') \$weight = (int)\$matches[1] * 2.2;
else echo 'Wrong units entered';
``````

You could do something similar to the following, in the example, we convert the value to grams.

``````
<?php
\$converter = new ConverterManager();
\$converter->registerConverter(new KiloConverter());
\$converter->registerConverter(new PoundConverter());

echo \$converter->convert('1lbs');       #453.59237
echo \$converter->convert('1.8lb');      #816.466266
echo \$converter->convert('1.34kgs');    #746.268656716
echo \$converter->convert('1kg');        #1000

class ConverterManager
{
protected
\$converters = array();

public function convert(\$subject){
foreach(\$this->converters as \$converter){
if(\$converter->canProcess(\$subject)){
return \$converter->process(\$subject);
}
}
return false;
}

public function registerConverter(\$converter){
array_push(\$this->converters, \$converter);
return \$this;
}
}

class KiloConverter
{
public function canProcess(\$subject){
return 1 === preg_match('~([0-9.]+)(?=kgs?)~i', \$subject);
}

public function process(\$subject){
preg_match('~([0-9.]+)(?=kgs?)~i', \$subject, \$match);
return 1000 / \$match[0];
}
}

class PoundConverter
{
public function canProcess(\$subject){
return 1 === preg_match('~([0-9.]+)(?=lbs?)~i', \$subject);
}

public function process(\$subject){
preg_match('~([0-9.]+)(?=lbs?)~i', \$subject, \$match);
return 453.59237 * \$match[0];
}
}

``````
Off Topic:

Ha, it appears Raffles solution is scarily close to mine!

Simple solution would be the way how you present to the users.
If you show the form as:
Enter Weight [text field] Kg
Enter Height [text field] cm
then user are restricted to enter the detail in the specified format.