删除彼此相邻的重复字符 [英] removing duplicate characters next to each other

查看:160
本文介绍了删除彼此相邻的重复字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im试图删除彼此直接相邻的重复字符

im trying to remove duplicate characters that are directly next to each other

1,2,3,4,5-有几个逗号,但不要删除它们 1,,2,,3,,4,,5-无论每个数字之间要有多少个逗号,我都希望只将其变成一个常规的1,2,3,4,5.我有类似的东西,可以确保在字符串的末尾没有逗号:

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,

谢谢:)

推荐答案

看起来您只想用逗号来做,因此使用

Looks like you only want to do this with commas, so it's extremely easy to do with preg_replace:

$n = '1,2,,3,,,,,4,5';
$n = preg_replace('/,+/', ',', $n);     // $n == '1,2,3,4,5'

您还可以使用 rtrim .这样会更快更容易阅读:

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:

$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, ','));

这篇关于删除彼此相邻的重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆