Rakhitha Nimesh
Rakhitha Nimesh

Reputation: 1451

How to identify mail addresses of specific domain using Regular expressions?

I want to wrap some html elements for gmail address in a given string. How can i do it with php regex.

Input

$string = 'Sample text [email protected] another text [email protected],[email protected]';

Output I want

$string = "Sample text <div class='gmail'>[email protected]</div> another text <div class='gmail'>[email protected]</div>,[email protected]";

Upvotes: 0

Views: 305

Answers (3)

Godwin
Godwin

Reputation: 9907

preg_replace('(\w+?@\w+?\.\w+)', '<div class="gmail">$0</div>', 'Sample text [email protected] another text [email protected],[email protected]');

Upvotes: 1

mario
mario

Reputation: 145482

You can take practically any email search regex and just replace the domain part with a fixed string. Then searching and replacing isn't much effort:

 = preg_replace('/\b\w[\w+.%!-][email protected]\b/', "<div class=gmail>$0</div>", $src);
                      # ^^^ allowed special chars still insufficient

Upvotes: 2

Niels
Niels

Reputation: 49919

Try something like (wraps all email adresses):

$string = 'Sample text [email protected] another text [email protected],[email protected]';
echo preg_replace("/([\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-])+/i", "<div class='gmail'>$1</div>", $string);

Gmail only:

$string = 'Sample text [email protected] another text [email protected],[email protected]';
echo preg_replace("/([\._a-zA-Z0-9-][email protected])+/i", "<div class='gmail'>$1</div>", $string);

Upvotes: 2

Related Questions