sortof
sortof

Reputation: 541

How to grab number/float from a string

I want to get the (first) price of each string row, with out the $ sign and it could be an int or float and there could be more numbers in the row.

example:

$str_array=(
"Up to $1.9 per Install in RU",
"1.3 per iOS Install in UAE and SA",
"$2.1 per iOS and Android Registration in US",
"Up to $2.5 per Android Install in 7 countries",
"Up to $1 per iOS Install in SA"
);

Expected output:

1.9
1.3
2.1
2.5
1

I tried something like this

$re = '/[+-]?([0-9]*[.])?[0-9]+/';
$str = 'Up to $2.5 per Android Install in 7 countries';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);   

and i get this

[0] => Array
    (
        [0] => 2.5
        [1] => 2.
    )

[1] => Array
    (
        [0] => 7
    )

but its not working good. :(

Upvotes: 0

Views: 48

Answers (3)

Sahil Gulati
Sahil Gulati

Reputation: 15141

Hope this will help you out,

Regex: \d+(?:\.\d+)?

1. \d+ this will match digits

2. (?:\.\d+)? this will optionally match decimal part

Try this code snippet here

<?php
ini_set('display_errors', 1);

$str_array=array(
"Up to $1.9 per Install in RU",
"1.3 per iOS Install in UAE and SA",
"$2.1 per iOS and Android Registration in US",
"Up to $2.5 per Android Install in 7 countries",
"Up to $1 per iOS Install in SA"
);
$result=array();
foreach($str_array as $string)
{
    preg_match_all('/[\d]+(?:\.[\d]+)?/',$string,$matches);
    $result[]=$matches[0][0];
}
print_r($result);

Output:

Array
(
    [0] => 1.9
    [1] => 1.3
    [2] => 2.1
    [3] => 2.5
    [4] => 1
)

Upvotes: 0

arkascha
arkascha

Reputation: 42959

Here is my version:

<?php
$data = [
    'Up to $1.9 per Install in RU',
    '1.3 per iOS Install in UAE and SA',
    '$2.1 per iOS and Android Registration in US',
    'Up to $2.5 per Android Install in 7 countries',
    'Up to $1 per iOS Install in SA'
];

array_walk($data, function(&$line){
    preg_match('/(\d+(?:\.\d+)?)/', $line, $tokens);
    if (count($tokens)>1) {
        var_dump(floatval($tokens[1]));
    }
});

The output obviously is:

float(1.9)
float(1.3)
float(2.1)
float(2.5)
float(1)

Upvotes: 1

splash58
splash58

Reputation: 26153

To select only the first number in a line add condition that there is no digit before

^(?:[^\d]+)([+-]?(?:[0-9]*[.])?[0-9]+)

demo and explanation

Upvotes: 0

Related Questions