0

I have the folowing regex code in php that its find and replace all repeating characters.

        $parts = explode("@", 'aaabbbddddeeesd@yahoo.com');
        $username = $parts[0];
        $domain = $parts[1];
        $out = preg_replace('/(.)\1+/', '$1', $username);
        $email = $out . '@' . $domain;

        print_r($email);

This code is replacing all repeating characters, but i need only to replace only for the first group from the beginning of the string.

Example aaabbbddddeeesd@yahoo.com i need the output to be abbbddddeeesd@yahoo.com

I have tried different regex but only this was working until now.

Thanks

PixelArtie
  • 31
  • 8
  • 1
    Very odd requirement, but you would need to anchor your required replacement character to the beginning of the string: `/^(.)\1+/` – jeroen Mar 31 '19 at 19:13
  • See the documentation for [`preg_replace`](https://www.php.net/manual/en/function.preg-replace.php), particularly the `$limit` argument. – lurker Mar 31 '19 at 19:17
  • By `first group` do you mean what comes before `@`? So `aaabbbddddeeesd` should become `abdesd`? – revo Mar 31 '19 at 19:43
  • Either `preg_replace('/(.)\1+/', '$1', $s, 1)` or `preg_replace('/^(.)\1+/', '$1', $s)` – Wiktor Stribiżew Mar 31 '19 at 20:54

1 Answers1

1

Rather than using a regex, you can instead extract the first character of the username (using $username[0]) and ltrim() it off the string, and put 1 occurrence of it back in...

$out = $username[0].ltrim($username, $username[0]);
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55