PHP:如果是数字(用逗号),将其转换为正确的数字格式(带点)

cho*_*ata 7 php regex number-formatting

我有一系列混合值:

$row = array('Unspecified risk','Yes','8','3','2','13','none','-1,49','-2,51','-1,46','-1,54'); -1,94   -1,55
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它包含文本以及正面和正面的逗号.

我需要将数值转换为正确的数字格式,并保持文本值不变.

现在我循环遍历值:

foreach ($row as $value) {
    // If $value is numeric, convert it to the 
    // right number format for use with MySQL (decimal(10,2))
    // If not, leave it be.
}
Run Code Online (Sandbox Code Playgroud)

我调查了两个相关的问题,但找不到合适的解决方案.

谁能提供一个实际的例子吗?

ale*_*ion 8

您不需要使用正则表达式.

使用str_replace()时需要替换','for a '.',然后使用intval()floatval()函数来获取数值.你也可以strstr()用来寻找'.'并决定是否使用intval()floatval()

例:

$row = array('Unspecified risk', 'Yes', '8', '3', '2', '13', 'none', '-1,49', '-2,51', '-1,46', '-1,54');

    function toNumber($target){
        $switched = str_replace(',', '.', $target);
        if(is_numeric($target)){
            return intval($target);
        }elseif(is_numeric($switched)){
            return floatval($switched);
        } else {
            return $target;
        }
    }

    $row = array_map('toNumber', $row);

    var_dump($row);
Run Code Online (Sandbox Code Playgroud)

我们使用str_replace()来替换逗号的点,这样它就是一个国际符号浮点数,即使它是在字符串上,这样我以后可以检查它是否为数字is_numeric()< - 这个函数很棒,因为它检测到了字符串,如果它是一个数字,无论是整数还是浮点数等.

我们使用is_numeric来检查值是整数浮点数还是文本并使用intval()或返回相应的值floatval()(没有应用替换的值将不会作为有效数字返回,只有在切换之后,并且.它将返回true作为数字) .

我们使用$row = array_map('toNumber', $row);将更改应用于数组.

利润xD