How can i remove duplicate commas used in string.
String = ",a,b,c,,,d,,"
I tried rtrim and itrim functions and removed the unwanted commas from beginning and ending .How can i remove duplicate commas ?
How can i remove duplicate commas used in string.
String = ",a,b,c,,,d,,"
I tried rtrim and itrim functions and removed the unwanted commas from beginning and ending .How can i remove duplicate commas ?
尝试这个:
$str = preg_replace('/,{2,}/', ',', trim($str, ','));
将trim
删除开始和尾随逗号,而preg_replace
将删除重复的逗号。
此外,正如@Spudley 建议的那样,正则表达式/,{2,}/
可以替换为/,,+/
它也可以工作。
编辑:
如果逗号之间有空格,您可以尝试在上一行之后添加以下行:
$str = implode(',', array_map('trim', explode(',', $str)))
我认为你可以爆炸你的字符串,然后创建一个只获取相关数据的新字符串
$string = ",a,b,c,,,d,,";
$str = explode(",", $string);
$string_new = '';
foreach($str as $data)
{
if(!empty($data))
{
$string_new .= $data. ',';
}
}
echo substr_replace($string_new, '', -1);
这将输出
a,b,c,d
已编辑
如果您遇到空格问题,可以尝试使用此代码
$string = ",a,b,c, ,,d,,";
$str = explode(",", str_replace(' ', '', $string));
$string_new = '';
foreach($str as $data)
{
if(!empty($data))
{
$string_new .= $data. ',';
}
}
echo substr_replace($string_new, '', -1);
这应该解决空间问题
可能不是很快,但一个简单的方法可能是:
$str = "a,b,c,,,d";
$str2 = "";
while($str <> $str2) {
$str2 = $str;
$str = str_replace(',,', ',', $str);
}
<?php
$str = ",a,b,c,,,d,,"
echo $str=str_replace(',,','',$str);
?>
输出: ,a,b,c,d
<?php
$str = ",a,b,c,,,d,,"
echo $str=trim(str_replace(',,','',$str),',');
?>
输出: a,b,c,d