指示客户仅输入
数字逗号数字逗号
(没有设定长度,但通常<10),他们输入的结果是,不可预测的。
给出以下示例输入:
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
但是在我继续扔东西之前......有一种优雅的方式,可能来自正则表达式的boffin!
答案 0 :(得分:3)
纯粹是抽象的意义,这就是我要做的事情:
$test = array_filter(array_map('trim',explode(",",$test)),'is_numeric')
实施例: http://sandbox.onlinephpfunctions.com/code/753f4a833e8ff07cd9c7bd780708f7aafd20d01d
答案 1 :(得分:1)
<?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
?>
答案 2 :(得分:1)
以下是使用正则表达式的示例
$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]
,您应该在路上
如果您不需要负数,只需删除正则表达式规则中的第一位。