D
D
Dimas1232016-01-07 16:30:01
PHP
Dimas123, 2016-01-07 16:30:01

How to extract the price from a string?

There are lines from which you need to isolate the price in the format number-point-fractional part (if any).

$12.34 -> 12.34
$12.34 -> 12.34
$12.00 -> 12.00
$12 -> 12
12€ -> 12
12.11€ -> 12.11
12.999€ -> 12.99
12.9€ -> 12.9
Extra:
£999.99€(2) -> 999.99
_ per piece (3) ->
999.99 RUB 999.99 per ton (33) -> 999.99

I found a code that does this (except additionally) in a language unknown to me:
private static String getPrice(String input)
{
    String output = "";

    Pattern pattern = Pattern.compile("\\d{1,3}[,\\.]?(\\d{1,2})?");
    Matcher matcher = pattern.matcher(input);
    if (matcher.find())
    {
        output = matcher.group(0);
    }

    return output;
}

This code doesn't work for me in php.
preg_match("\\d{1,3}[,\\.]?(\\d{1,2})?", $str, $matches);
$price = $matches[0];

//Сам я делаю вот так:
preg_match('/\d+\.?\d*/', $str, $matches);
/* но это очень простой код, здесь не учитывается запятая вместо точки 
и скорее всего дополнительные примеры не обработаются нормально, 
например этот "999,99 Руб. за тонну (33)" */
$price = $matches[0];

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim, 2016-01-07
@Dimas123

Here is the regular expression from your example
UPD: Here is a link where it is convenient to test regular expressions regexr.com/3chi4

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question