在PHP中,过滤小数中的无效字符是一个常见的任务,比如去除小数点前后的空格、或者移除小数点后面的无效零。以下是一个简单的PHP实例,展示如何实现这一功能。

实例描述

假设我们有一个包含小数的字符串,我们需要过滤掉其中的无效字符,例如空格、多余的零等。

PHP实例:过滤小数中的无效字符 客厅装修

实例代码

```php

function filterDecimal($decimal) {

// 移除小数点前后的空格

$decimal = trim($decimal);

// 移除小数点后面的无效零

$decimal = preg_replace('/("".""d*?)0+$/', '$1', $decimal);

// 如果小数点前后都是零,则返回0

if (strpos($decimal, '.') !== false && $decimal == '0.' || $decimal == '.0') {

return '0';

}

return $decimal;

}

// 测试数据

$testDecimals = [

' 123.4500 ' => '123.45',

' 0.0000 ' => '0',

' 000.0000 ' => '0',

' 123.00 ' => '123',

' .000 ' => '0',

' 123. ' => '123',

' .123 ' => '0.123'

];

// 输出结果

foreach ($testDecimals as $input => $expected) {

$filtered = filterDecimal($input);

echo "