开发者

replace . from email address

I have a tex开发者_如何转开发t string. That may or maynot contain email addresses. I want to replace all . (fullstop) to dot.

blah blah abcd@gmail.com  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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜