0

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

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

I need to remove duplicate @ and get something like:

ABCC@CmCCCCmCCmCCDEF (I need only first @)

How to do that?

4
  • 1
    First of all, tell us what you have tried Commented Nov 3, 2013 at 23:20
  • strpos + substr_replace, no need to use regular expressions (especially if you cannot write one - it will be painful for you to maintain this code) Commented Nov 3, 2013 at 23:22
  • @zerkms: it can be a good way, you must only skip the first one. Commented Nov 3, 2013 at 23:24
  • @Casimir et Hippolyte: it can be, but as I said - it's always a good idea to always write a code you're able to maintain. Otherwise OP will be a frequent visitor here for every trivial change. And, no, I don't think it's a good way to learn. Commented Nov 3, 2013 at 23:26

2 Answers 2

4

A regex way:

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

details:

(?:           # 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 @
Sign up to request clarification or add additional context in comments.

2 Comments

Isn't that an atomic group ? Anyways +1000 :)
@HamZa: yes it is, and it can by replaced by (?:...) since it is useless with an alternation inside.
3

Give this a try:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.