Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract floating point numbers from a string in PHP

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
like image 390
Tian Bo Avatar asked Jun 03 '09 12:06

Tian Bo


People also ask

How do I get the number of digits in a string in PHP?

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.

How can I convert string to float in PHP?

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.

How does PHP calculate float value?

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.

What is parseFloat in PHP?

The parseFloat() function parses a string argument and returns a floating point number.


3 Answers

$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.

like image 56
cletus Avatar answered Oct 11 '22 02:10

cletus


<?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
)
like image 45
nonopolarity Avatar answered Oct 11 '22 02:10

nonopolarity


$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 ) 
like image 35
Paolo Bergantino Avatar answered Oct 11 '22 01:10

Paolo Bergantino