im trying to remove duplicate characters that are directly next to each other
1,2,3,4,5 – has a few commas but they are not to be removed
1,,2,,3,,4,,5 – would have to be turned into the regular 1,2,3,4,5 no matter how many commas are inbetween each number i would like to have just one. i have something similar which makes sure there are no commas at the end of the string:
$n = "1,2,3,4,5";
for ($i=0;$i< strlen($n);$i++) {
if (substr($n, -1) == ',') {
$n = substr($n, 0, -1);
}
}
would appreciate some help on this matter,
Thanks 🙂
Looks like you only want to do this with commas, so it’s extremely easy to do with preg_replace:
Also you can replace the code you gave above that makes sure there are no commas at the end of a string with rtrim. It will be faster and easier to read:
You can combine them both into a one-liner: