【问题标题】:Removing duplicate characters in string preg_replace删除字符串 preg_replace 中的重复字符
【发布时间】:2013-11-03 23:18:00
【问题描述】:

$value = "ABCC@CmCCCCm@CCmC@CDEF";

$clear = preg_replace('/@{1,}/', "", $value);

我需要删除重复的 @ 并得到类似的东西:

ABCC@CmCCCCmCCmCCDEF(我只需要第一个@)

怎么做?

【问题讨论】:

  • 首先,告诉我们你尝试了什么
  • strpos + substr_replace,不需要使用正则表达式(特别是如果你不会写——维护这段代码会很痛苦)
  • @zerkms:这可能是个好方法,你只能跳过第一个。
  • @Casimir et Hippolyte:可以,但正如我所说 - 始终编写您能够维护的代码总是一个好主意。否则 OP 将成为每一个微不足道的变化的常客。而且,不,我认为这不是一个好的学习方式。

标签: php regex preg-replace


【解决方案1】:

正则表达式方式:

$clear = preg_replace('~(?>@|\G(?<!^)[^@]*)\K@*~', '', $value);

详情:

(?:           # open a non capturing group
    @         # literal @
  |           # OR
    \G(?<!^)  # contiguous to a precedent match, not at the start of the string
    [^@]*     # all characters except @, zero or more times
)\K           # close the group and reset the match from the result
@*            # zero or more literal @

【讨论】:

  • 那不是原子团吗?无论如何+1000 :)
  • @HamZa: 是的,它可以被(?:...) 替换,因为它在里面有一个替换是没用的。
【解决方案2】:

试试这个:

// The original string
$str = 'ABCC@CmCCCCm@CCmC@CDEF';
// Position of the first @ sign
$pos = strpos($str, '@');
// Left side of the first found @ sign
$str_sub_1 = substr($str, 0, $pos + 1);
// Right side of the first found @ sign
$str_sub_2 = substr($str, $pos);
// Replace all @ signs in the right side
$str_sub_2_repl = str_replace('@', '', $str_sub_2);
// Join the left and right sides again
$str_new = $str_sub_1 . $str_sub_2_repl;
echo $str_new;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 2018-02-20
    相关资源
    最近更新 更多