将字符串清理成逗号分隔数字的最优雅方法
Most elegant way to clean a string into only comma separated numerals
指示客户仅输入后
number comma number comma number
(没有固定长度,但通常 < 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!
在纯粹抽象的意义上,这就是我要做的:
$test = array_filter(array_map('trim',explode(",",$test)),'is_numeric')
示例:
http://sandbox.onlinephpfunctions.com/code/753f4a833e8ff07cd9c7bd780708f7aafd20d01d
<?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
?>
这是一个使用正则表达式的例子,
$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]
,您应该已经上路了。
如果您不需要负数,只需删除正则表达式规则中的第一位。
指示客户仅输入后
number comma number comma number
(没有固定长度,但通常 < 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!
在纯粹抽象的意义上,这就是我要做的:
$test = array_filter(array_map('trim',explode(",",$test)),'is_numeric')
示例: http://sandbox.onlinephpfunctions.com/code/753f4a833e8ff07cd9c7bd780708f7aafd20d01d
<?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
?>
这是一个使用正则表达式的例子,
$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]
,您应该已经上路了。
如果您不需要负数,只需删除正则表达式规则中的第一位。