【问题标题】:Most elegant way to clean a string into only comma separated numerals将字符串清理为仅以逗号分隔的数字的最优雅方法
【发布时间】:2025-12-06 22:55:01
【问题描述】:

指示客户只输入后

数字逗号数字逗号数字

(没有设定长度,但一般

给定以下示例输入:

3,6 ,bannana,5,,*,

我怎样才能最简单,可靠地结束:

3,6,5

到目前为止,我正在尝试一种组合:

$test= trim($test,","); //Remove any leading or trailing commas
$test= preg_replace('/\s+/', '', $test);; //Remove any whitespace
$test= preg_replace("/[^0-9]/", ",", $test); //Replace any non-number with a comma

但在我继续向它扔东西之前......有没有一种优雅的方式,可能来自正则表达式研究人员!

【问题讨论】:

  • 我认为不只是清理输入,你还应该使用javascript进行输入验证
  • 这是个好主意,我没想到!
  • 你也可以让浏览器通过输入类型号developer.mozilla.org/en-US/docs/Web/HTML/Element/Input来处理这个问题
  • @rypskar 但是允许逗号吗?
  • @mayersdesign 如果您在输入中使用pattern,您可以指定一个正则表达式来允许。请记住,IE 可能不支持此功能(也可能不支持 safari,因为输入验证属性有点奇怪)

标签: php regex string preg-replace


【解决方案1】:

在纯粹抽象的意义上,这就是我要做的:

$test = array_filter(array_map('trim',explode(",",$test)),'is_numeric')

示例: http://sandbox.onlinephpfunctions.com/code/753f4a833e8ff07cd9c7bd780708f7aafd20d01d

【讨论】:

  • 这很有趣,尤其是我想以数组结尾
  • 这对我来说非常有效,非常感谢。我确实假设用户打算将点输入为逗号,因此为此使用了 preg_replace,然后使用您的代码转换为数组。现在还将根据上面的评论添加 javascript 验证。再次感谢。
【解决方案2】:
<?php
$str = '3,6 ,bannana,5,,*,';
$str = explode(',', $str);
$newArray = array_map(function($val){
    return is_numeric(trim($val)) ? trim($val) : '';
}, $str);
print_r(array_filter($newArray)); // <-- this will give you array
echo implode(',',array_filter($newArray)); // <--- this give you string
?>

【讨论】:

  • 我明白了这个想法,非常感谢,但对于我认为的正则表达式剥离练习来说,似乎有很多代码。您能否解释一下为什么不能以“简单”的方式完成?
  • 因为字符串有数字、单词、空格。所以我们需要修剪、检查数字和过滤。
  • 实际上与接受的答案的代码量相同。
【解决方案3】:

这是一个使用正则表达式的示例,

$string = '3,6 ,bannana,5,-6,*,';

preg_match_all('#(-?[0-9]+)#',$string,$matches);

print_r($matches);

会输出

Array
(
    [0] => Array
        (
            [0] => 3
            [1] => 6
            [2] => 5
            [3] => -6
        )

    [1] => Array
        (
            [0] => 3
            [1] => 6
            [2] => 5
            [3] => -6
        )

)

使用$matches[0],您应该可以上路了。
如果您不需要负数,只需删除正则表达式规则中的第一位即可。

【讨论】:

  • 非常感谢,我知道会有一个正则表达式的方式......总是有!哈哈
最近更新 更多