为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
临摹微笑 2023-10-01 17:12:32
我想从输入字段获取字符串,然后对其进行格式化和清理。我想要得到的字符串是用逗号分隔的自然数,没有任何空格。首先,我想删除所有空格和最后一个逗号。我的意思是,如果格式化的字符串与我想要的不匹配,我希望它返回空字符串。//OK examples(without any spaces)1,2,123,45,7132,1,555,678//NG examplesaaa,111,23651,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”。抱歉我的解释很混乱......
查看完整描述

2 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

替换空格并修剪开头或结尾的逗号和空格:

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

或者:

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

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

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

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


查看完整回答
反对 回复 2023-10-01
?
慕妹3242003

TA贡献1824条经验 获得超6个赞

使用

\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

                           string

PHP:


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


查看完整回答
反对 回复 2023-10-01
  • 2 回答
  • 0 关注
  • 110 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信