I think you can just blow your string and then create a new one, getting only the relevant data
$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);
This will lead to the conclusion
a,b,c,d
edited
If you have problems with spaces, you can try using this code
$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);
This should solve the problem with spaces