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:
1,2,3,4,5 - 有几个逗号,但它们不被删除1,2,3,4,,5 - 必须变成常规1,2,3,4 ,5无论每个数字之间有多少逗号,我都希望只有一个。我有类似的东西,以确保字符串末尾没有逗号:
$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 :)
2 个解决方案
#1
33
Looks like you only want to do this with commas, so it's extremely easy to do with preg_replace:
看起来你只想用逗号来做这个,所以使用preg_replace非常容易:
$n = '1,2,,3,,,,,4,5';
$n = preg_replace('/,+/', ',', $n); // $n == '1,2,3,4,5'
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:
您也可以替换上面给出的代码,以确保在使用rtrim的字符串末尾没有逗号。它会更快更容易阅读:
$n = '1,2,3,4,5,,,,,'
rtrim($n, ','); // $n == '1,2,3,4,5'
You can combine them both into a one-liner:
你可以将它们组合成一个单行:
$n = preg_replace('/,+/', ',', rtrim($n, ','));
#2
12
$n = '1,2,,3,,,,,4,5';
$n = preg_replace('/(.)\\1+/', '$1', $n);
This should work for any duplicate characters immediately following one another.
这应该适用于紧随其后的任何重复字符。
However, it is unlikely that the asker wants to replace any character repetitions in this way (including numbers like 44 => 4). More likely, something like this is intended:
但是,提问者不太可能以这种方式替换任何字符重复(包括44 => 4之类的数字)。更有可能的是,这样的意图是:
$n = preg_replace('/([,.;])\\1+/', '$1', $n); # replace repetitions of ,.:
$n = preg_replace('/([^\d])\\1+/', '$1', $n); # replace repetitions of non-digit characters
#1
33
Looks like you only want to do this with commas, so it's extremely easy to do with preg_replace:
看起来你只想用逗号来做这个,所以使用preg_replace非常容易:
$n = '1,2,,3,,,,,4,5';
$n = preg_replace('/,+/', ',', $n); // $n == '1,2,3,4,5'
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:
您也可以替换上面给出的代码,以确保在使用rtrim的字符串末尾没有逗号。它会更快更容易阅读:
$n = '1,2,3,4,5,,,,,'
rtrim($n, ','); // $n == '1,2,3,4,5'
You can combine them both into a one-liner:
你可以将它们组合成一个单行:
$n = preg_replace('/,+/', ',', rtrim($n, ','));
#2
12
$n = '1,2,,3,,,,,4,5';
$n = preg_replace('/(.)\\1+/', '$1', $n);
This should work for any duplicate characters immediately following one another.
这应该适用于紧随其后的任何重复字符。
However, it is unlikely that the asker wants to replace any character repetitions in this way (including numbers like 44 => 4). More likely, something like this is intended:
但是,提问者不太可能以这种方式替换任何字符重复(包括44 => 4之类的数字)。更有可能的是,这样的意图是:
$n = preg_replace('/([,.;])\\1+/', '$1', $n); # replace repetitions of ,.:
$n = preg_replace('/([^\d])\\1+/', '$1', $n); # replace repetitions of non-digit characters