2

我在名为“alerts”的数据库列中关注了字符串

$string = '1,2,,3,4,5,,,6';

我将如何检查这个字符串在数字之间是否有两个或多个逗号,以及如何删除额外的逗号以使字符串像这样;

$string = '1,2,3,4,5,6';
4

4 回答 4

3

您应该为此使用正则表达式。

preg_replace('/,,+/', ',', $string);

如果你不熟悉正则表达式,你应该谷歌它。有大量的教程,一旦你熟悉了它们,你就可以用它们做很多事情。

于 2013-10-07T12:14:05.507 回答
2

使用此代码:

$string = '1,2,,3,4,5,,,6';
$arr=explode(",",$string);
$string=implode(",",array_filter($arr));

或者,在一行中

$string = implode(",",array_filter(explode(",",$string)));
于 2013-10-07T12:13:04.217 回答
0

This would also work, without having the overhead of loading the regular expression engine.

$string = '1,2,,3,4,5,,,6';

do {
    $string = str_replace(',,', ',', $string, $count);
} while ( $count > 0 );

echo $string;

Output:

  1,2,3,4,5,6
于 2013-10-07T12:20:51.937 回答
0

试试这个:

$text = '1,2,,3,4,5,,,6,,2,,1,,2,9';
$textArray = preg_split("/[,.]+/", $text);
$textArray = array_filter($textArray);
echo implode(",", $textArray);

Output:1,2,3,4,5,6,2,1,2,9

如果你想要独特的元素,那么第二行将是

$textArray = array_unique(preg_split("/[,.]+/", $text));
于 2013-10-07T12:20:40.253 回答