Jump to content

Extracting and converting numbers from text strings


king.oslo

Recommended Posts

Hello my friends,

 

I am trying to make a Body Mass Index (BMI) calulator. It works so that users feed the calulator with their weight and height, and their BMI is calculated. Unfortunatly the way that people feed the calculator with their data seems to vary big time.

 

For example, they may wright that their height is:

 

150cm

1.5meters

ca 150cm

150

..and so on.

 

I need to find some functions or ways to get rid of letters, and convert the ones given in centimeters to meters.

 

Which functions or methods can I use?

 

Thanks :)

 

Marius

But there's no foolproof solution, because you'd have to take every possible input into account. Here's my shot at a function:

 

<?php
function smart_convert_m($str) {
preg_match('~^([\d,.]+)\s*([a-z.]+)$~iD', trim($str), $matches);
$value = (float) str_replace(',', '.', $matches[1]);
switch ($matches[2]) {
	case 'cm':
	case 'cm.':
	case 'centimetres':
	case 'centimeters':
		$m = $value / 100;
		break;
	case 'm':
	case 'm.':
	case 'metres':
	case 'meters':
		$m = $value;
		break;
	default:
		return false;
}
return $m;
}
//test with samples
$samples = array('1,5 metres', '1.5meters', '1.5m', '150cm', '150centimetres', '150 centimeters');
foreach ($samples as $sample) {
echo "$sample => " . smart_convert_m($sample) . '<br />';
}
?>

Output:

 

1,5 metres => 1.5
1.5meters => 1.5
1.5m => 1.5
150cm => 1.5
150centimetres => 1.5
150 centimeters => 1.5

 

Edit: Added support for cm and m with a trailing dot.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.