2013-10-07 28 views
2

我跟随一个名为数据库列字符串“警报”检查字符串中有两个或多个逗号和删除其他逗号

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

我怎么会去检查,如果该字符串有两个或多个逗号在数字之间,我怎样才能删除额外的逗号来制作这样的字符串;

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

http://stackoverflow.com/questions/14417951/remove-multiple-commas-regex/14436269#14436269 – djot

+0

http://stackoverflow.com/questions/16687389/explode-do-not-work-with-multilpe-commas-inside-the-string/16687505#16687505 – djot

回答

2

使用此代码:

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

,或者在一个行

$string = implode(",",array_filter(explode(",",$string))); 
+0

它的工作原理,你有一个很好的编码背景Patel :) – user2854563

+0

['preg_replace'](http:// stackoverflow .com/a/19224638/67332)比这更快(3种不同的功能)。 –

3

你应该使用正则表达式为。

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

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

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

如果你想独特的元素,然后2号线将

$textArray = array_unique(preg_split("/[,.]+/", $text)); 
+0

如果花车也在文本中,此示例将无效。 –

0

这也将工作,而无需加载正规的开销表达引擎。

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

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

echo $string; 

输出:

1,2,3,4,5,6 
+0

它输出什么?对不起,我没有测试过,只想知道我的PHP知识增加。谢谢! – user2854563

相关问题