Reputation: 1911
I have a text string. That may or maynot contain email addresses. I want to replace all . (fullstop) to dot.
blah blah [email protected] fooo some content and email again
to
blah blah abcd@gmail dot com fooo some content and email again
Can I do this using regex?
-Thanks Arun
Upvotes: 0
Views: 564
Reputation: 336238
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
.
Upvotes: 3
Reputation: 818
Step one Regex Get Email handle from Email Address and / or https://stackoverflow.com/questions/36261/test-expand-my-email-regex
Step two regex to replace "foo-some white space-bar" with "fubar"
Taking the teach a man to fish approach.
Upvotes: 0