If you had the .NET regex engine at your disposal, you could do it in a single regex by searching for (?:.(?=\S+@)|(?<=@\S+).)
and replacing all matches with dot
.
In PHP, you'd have to do it in two steps/iteratively:
Search for \.(?=\S+@)
and replace with dot
:
$subject = preg_replace('/\.(?=\S+@)/', ' dot ', $subject);
This will replace all dots in email addresses that occur before the @
. Then search for (@\S+)\.
and replace with \1 dot
; repeat this until there are no further matches.
Something like
while (preg_match('/(@\S+)\./', $subject)) {
$subject = preg_replace('/(@\S+)\./', '\1 dot ', $subject);
}
This will match a dot inside an email address after the @
, but since PHP's regex engine doesn't support infinite lookbehind, I need to reapply the regex to the string as many times as the maximum number of dots after the @
. For example, in the string @foo.bar.com
, it will first match @foo.bar.
and replace with @foo.bar dot
. Then, in the next run, it replaces @foo.
with @foo dot
.