如何从字符串中删除最后一个逗号和所有空格,然后使用 PHP 对其进行清理?

How can I remove last comma and all spaces from string, then sanitize it using PHP?

我想从输入字段中获取字符串,然后对其进行格式化和清理。

我要获取的字符串是自然数,用逗号分隔,没有空格。 首先,我想删除所有空格和最后一个逗号。 我的意思是,如果格式化的字符串与我想要的不匹配,我希望它成为 return 空字符串。

//OK examples(without any spaces)
1,2,123,45,7
132,1,555,678
//NG examples
aaa,111,2365
1,2,123,45,7,
-1,2,123,45,7,,,
1, 2, 123, 45,  7

首先我想删除空格和最后一个逗号 1, 235, 146, => 1,235,146

我试过下面的代码

$input = str_replace(' ', '', $input);
rtrim($input, ',');
if (preg_match('/^\d(?:,\d+)*$/', $input)) {
    return $input;
}
return '';

这个,如果字符串在最后一个逗号后有空格,它return是空字符串。

1,2,123,45,7,   => //returns empty string.

我想将其格式化为“1,2,123,45,7”。

抱歉我乱七八糟的解释...

使用

\s+|,+\s*$

proof

解释

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
 |                        OR
--------------------------------------------------------------------------------
  ,+                       One or more ','
--------------------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

PHP:

preg_replace('/\s+|,+\s*$/', '', $input)

替换开头或结尾的空格和 trim 逗号和空格:

$result = str_replace(' ', '', trim($string, ', '));

或者:

$result = trim(str_replace(' ', '', $string), ',');

那么如果你只想要数字和逗号(没有字母等)可能:

if(!preg_match('/^[\d,]+$/', $string)) {
    //error
}

但是,对于没有逗号的单个数字,这不会出错。