只允许数字数据和逗号,删除重复的逗号


php Allow only numeric data and comma, remove duplicate comma

我有一个脚本,我正在为一个自动任务工作,所以我不太担心干净的代码,因为它将只使用一次。

脚本读取平面文件并将信息存储到数组中,该数组稍后将用于从数据库中读取内容。

但是,我只想要数字数据,所以我使用了preg_replace()和逗号。我的代码如下:

这些是使用循环从平面文件中的值中读取的。

$store = array();
$store[] = 111;
$store[] = 2;
$store[] = 4;
$store[] = 55;
$store[] = 66;
$store[] = 'Kilory';
$store[] = 9090;
$theList[$i] = preg_replace( '/[^0-9,]/u', '', implode( ',', $store ) );
unset( $store );

得到的结果是0,2,4,55,66,9090。如果我试图使用mysql in()语句中的信息,它会吐出一个错误,因为有两个逗号在彼此旁边。删除相邻副本的最佳方法是什么?

谢谢!

重复逗号,包括标题和结尾逗号,您可以使用$string = trim(preg_replace('#,{2,}#', ',', $string), ',');删除。

PHP为此提供了一个过滤器函数:

$store = array();
$store[] = 111;
$store[] = 2;
$store[] = 4;
$store[] = 55;
$store[] = 66;
$store[] = 'Kilory';
$store[] = 9090;
$theList[$i] = implode(',', array_filter($store, 'is_numeric'));
unset($store);

在循环store[]值时,使用is_numeric()函数检查值是否为数字。如果是,则加逗号,如果不是,则不加。

手册