删除字符串preg_replace中的重复字符

时间:2013-11-03 23:18:00

标签: php regex preg-replace

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

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

我需要删除重复的@并获得类似的内容:

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

怎么做?

2 个答案:

答案 0 :(得分:3)

尝试一下:

// 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;

答案 1 :(得分:3)

正则表达方式:

$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 @