0

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

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

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

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

怎么做?

4

2 回答 2

4

正则表达式方式:

$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 @
于 2013-11-03T23:45:10.863 回答
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;
于 2013-11-03T23:39:11.063 回答