Parse currency from string

前端 未结 5 1507
无人及你
无人及你 2021-01-02 18:25

I want to parse a currency from a string in PHP, I\'ve had a look at number formatter but haven\'t got PHP 5.3 or the ability to add extensions.

The currency will on

相关标签:
5条回答
  • 2021-01-02 19:12

    I've got another answer. Might be a touch faster than using strpos, and would be better if there was any possibility of white space in the input.

    $input = "£250.75";
    $output = floatval(ltrim($input,"£"));
    echo $output;
    250.75
    

    You could also add other currencies to the char list in ltrim:

    $output = floatval(ltrim($input,"£$¢"));
    

    This would strip $ or £ or ¢ from the left side of your number, as well as white space, which would break the solution above which uses strpos. Also, this would give the same result if the currency symbol was left off in some cases.

    0 讨论(0)
  • 2021-01-02 19:14
    $price = (float) substr($input, 1, strlen($input) - 1);
    
    0 讨论(0)
  • 2021-01-02 19:15
    (float)substr($input, strpos($input, "£")+1);
    

    This will get you the following results:

    float(0.9)
    float(100)
    float(100.1)
    float(1000)
    float(153.93)
    

    EDIT: updated to reflect the change to question. this is assuming all strings are like the one you gave as an example.

    0 讨论(0)
  • 2021-01-02 19:25

    You could do it with a regular expression ($matches[1] will have your value):

    preg_match('/£([0-9]+|[0-9]+\.?[0-9]{2})/', $text, $matches);
    
    0 讨论(0)
  • 2021-01-02 19:26
    preg_match('/(?<=£)(?=[\d.]*\d)(\d*(?:\.\d*)?)/', $input, $matches);
    

    will find a match within any of these:

    • £.10
    • £0.10
    • £100
    • £100.00

    etc.

    0 讨论(0)
提交回复
热议问题