猿问

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

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


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


//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 '';

这个,如果字符串最后一个逗号后面有空格,则返回空字符串。


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

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


抱歉我的解释很混乱......


临摹微笑
浏览 121回答 2
2回答

UYOU

替换空格并修剪开头或结尾的逗号和空格:$result = str_replace(' ', '', trim($string, ', '));或者:$result = trim(str_replace(' ', '', $string), ',');那么如果你只想要数字和逗号(没有字母等)也许:if(!preg_match('/^[\d,]+$/', $string)) {     //error    }然而,这对于没有逗号的单个数字不会出错。

慕妹3242003

使用\s+|,+\s*$查看证明解释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                           stringPHP:preg_replace('/\s+|,+\s*$/', '', $input)
随时随地看视频慕课网APP
我要回答