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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With