I would like to convert a string of delimited dimension values into floating numbers.
For example
152.15 x 12.34 x 11mm
into
152.15, 12.34 and 11
and store in an array such that:
$dim[0] = 152.15;
$dim[1] = 12.34;
$dim[2] = 11;
I would also need to handle scenarios where the delimiting text is different and the numbers may be followed by a unit expression like:
152.15x12.34x11 mm
152.15mmx12.34mm x 11mm
Method 1: Using preg_match_all() Function. Note: preg_match() function is used to extract numbers from a string. Usually, the search starts from the beginning of the subject string. The optional parameter offset is used to specify the position from where to start the search.
Method 1: Using floatval() function. Note: The floatval() function can be used to convert the string into float values . Return Value: This function returns a float. This float is generated by typecasting the value of the variable passed to it as a parameter.
The is_float() function checks whether a variable is of type float or not. This function returns true (1) if the variable is of type float, otherwise it returns false.
The parseFloat() function parses a string argument and returns a floating point number.
$str = '152.15 x 12.34 x 11mm';
preg_match_all('!\d+(?:\.\d+)?!', $str, $matches);
$floats = array_map('floatval', $matches[0]);
print_r($floats);
The (?:...)
regular expression construction is what's called a non-capturing group. What that means is that chunk isn't separately returned in part of the $mathces
array. This isn't strictly necessary in this case but is a useful construction to know.
Note: calling floatval()
on the elements isn't strictly necessary either as PHP will generally juggle the types correctly if you try and use them in an arithmetic operation or similar. It doesn't hurt though, particularly for only being a one liner.
<?php
$s = "152.15 x 12.34 x 11mm";
if (preg_match_all('/\d+(\.\d+)?/', $s, $matches)) {
$dim = $matches[0];
}
print_r($dim);
?>
gives
Array
(
[0] => 152.15
[1] => 12.34
[2] => 11
)
$string = '152.15 x 12.34 x 11mm';
preg_match_all('/(\d+(\.\d+)?)/', $string, $matches);
print_r($matches[0]); // Array ( [0] => 152.15 [1] => 12.34 [2] => 11 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With