Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove comma from string in php

Tags:

php

suppose the value is

1,2,,4,5,6 - For this i can use str_replace(",,",",",$mystring) to get 1,2,4,5,6

How to get values like 2,4,5,6 from ,2,,4,5,6 where two or more consecutive commas are replaced by a single comma and if comma comes before any value it is neglected.If there is only commas like ,,,,,, then empty value is returned.

how to do this in php.

like image 702
Shakun Chaudhary Avatar asked Aug 10 '16 03:08

Shakun Chaudhary


2 Answers

You can explode the string by comma first and then implode after filtering the empty strings.

$val=",2,,4,5,6";
$parts=explode(",",$val);
$parts=array_filter($parts);
echo(implode(",",$parts));

Note that this will also filter 0 from your values. If you want to keep the zeros, refer this question

like image 172
Imesha Sudasingha Avatar answered Nov 14 '22 22:11

Imesha Sudasingha


You can do what you did on your first problem...

Then use trim() to remove unnecessary commas at the front or end of the string.

$mystring = ',2,,4,5,6';

$output = str_replace(',,', ',', $mystring);

echo trim($output, ',');

//Output will be: 2,4,5,6
like image 43
rmondesilva Avatar answered Nov 14 '22 23:11

rmondesilva