Handle number in string PHP

不打扰是莪最后的温柔 提交于 2020-01-17 15:15:06

问题


I have a text area, it include string and number.

I want to sum 3 record into a text like this

I try to show you my stack, hope you can help me. Thank you!


回答1:


I dont know, how to do that this would work with comma, but this code

If(isset($_POST['test'])) { //test is my textarea name
    $total = 0;
    $ex = explode(' ',$_POST['test']);
    function total ($ex) {
        global $total;
        return $total+=$ex;
    }
    array_map('total',$ex);
    echo $total;
}

Worked well, when you write normal integer without anything (for example - 3500) and double with a dot (for example - 3.5). I think this function is good enough to use it




回答2:


With a little regular expression

$s = "xxx = 230.5
bbb = 490.3
ccc = 3.948";

preg_match_all('/[,\.\d]+/', $s, $match);
print_r($match);
exit;

Result

Array
(
[0] => Array
    (
        [0] => 230.5
        [1] => 490.3
        [2] => 3.948
    )

)

Please regard: if you use comma and dot, you'll have to prepare the values for a valid floating point format.



来源:https://stackoverflow.com/questions/38584233/handle-number-in-string-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!