我在名为“alerts”的数据库列中关注了字符串
$string = '1,2,,3,4,5,,,6';
我将如何检查这个字符串在数字之间是否有两个或多个逗号,以及如何删除额外的逗号以使字符串像这样;
$string = '1,2,3,4,5,6';
您应该为此使用正则表达式。
preg_replace('/,,+/', ',', $string);
如果你不熟悉正则表达式,你应该谷歌它。有大量的教程,一旦你熟悉了它们,你就可以用它们做很多事情。
使用此代码:
$string = '1,2,,3,4,5,,,6';
$arr=explode(",",$string);
$string=implode(",",array_filter($arr));
或者,在一行中
$string = implode(",",array_filter(explode(",",$string)));
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
试试这个:
$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));