【发布时间】: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