How to remove unnecessary commas from a string?

How to remove duplicate commas used in a string.

String = ", a, b, c ,, d,"

I tried the rtrim and itrim functions and removed the unnecessary commas from the beginning and end. How to remove duplicate commas?

+6
source share
4 answers

Try the following:

$str = preg_replace('/,{2,}/', ',', trim($str, ',')); 

trim removes start and end commas, and preg_replace removes duplicates.

Look at the action!

Also, as @Spudley suggested, the regular expression /,{2,}/ can be replaced by /,,+/ , and it will work too.

EDIT:

If there are spaces between commas, you can try adding the following line after the above:

 $str = implode(',', array_map('trim', explode(',', $str))) 
+14
source

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 

Live demo

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

+4
source

Probably not a very fast, but simple method could be:

 $str = "a,b,c,,,d"; $str2 = ""; while($str <> $str2) { $str2 = $str; $str = str_replace(',,', ',', $str); } 
+2
source
 <?php $str = ",a,b,c,,,d,," echo $str=str_replace(',,','',$str); ?> 

Conclusion: A, b, c, d


 <?php $str = ",a,b,c,,,d,," echo $str=trim(str_replace(',,','',$str),','); ?> 

Conclusion: a, b, c, d

0
source

Source: https://habr.com/ru/post/946772/


All Articles