tags:

views:

45

answers:

3

Hello guys.

Please help with this little issue if you could.

I would like to search a string, if a match is made, I'd like to change the value to something else.

eg.

if (preg_match("gmail",$email)) {

// code needed to switch "gmail" for "googlemail"

}

This is needed because my mail server won't accept an email address in 'gmail.com' format.

Thanks in advance. Shane

A: 

Use preg_replace:

preg_replace("gmail", "googlemail", $email);
Tim Yates
Will this only alter the value $email if a match (gmail) is found?
shane
Yes. Like Galen said, though, you might as well use `str_replace` if you are doing a simple string replacement.
Tim Yates
+2  A: 

if you don't need regular expressions just use str_replace. No need to test either, just replace it.

str_replace( '@gmail.com', '@googlemail.com', $email );
Galen
This worked perfectly. Thank you very much.
shane
Shane: That code will change something like `[email protected]` to `[email protected]`.
Tim Cooper
+1  A: 

Just so it doesn't match something like [email protected]:

$email = preg_replace('/(.+)gmail(\..+)$/', '$1googlemail$2', $email);
Tim Cooper
this will change [email protected] to [email protected] and you forgot the trailing /
Galen
Why the `(\..+)$`? Are there other [TLD](http://en.wikipedia.org/wiki/Top-level_domain)s besides the `.com` of `gmail`?
Bart Kiers