Function: Fix Email - Replace Email within <> of a String

Authored by

I recently ran into a situation where I needed to update the From header of an outgoing email in PHP. Specifically, the header string contained a name and an email address wrapped in angle brackets, such as:

John Smith <oldemail@example.com>

The email data I was working with was stored inside an array structure (for example, $email['headers']['email']). My goal was to replace the existing email address inside the angle brackets (< >) with a new one while keeping the display name intact. To achieve this, I wrote a small helper function that uses regular expressions (preg_replace) to locate whatever text exists between < and > and substitute it with the new email address. This way, the function preserves the original formatting and any display name while seamlessly swapping in the updated address.

Here’s the function:

function fix_email($fromHeaderString, $newEmail) {
    return preg_replace('/<[^>]+>/', "<{$newEmail}>", $fromHeaderString);
}

The regular expression inside preg_replace is the key to making this work:

  • // – the forward slashes are just the delimiters that wrap the regex pattern.

  • < – matches the literal opening angle bracket.

  • [^>]+ – this means “one or more characters that are not a >.” In other words, it captures everything inside the angle brackets, up until the closing bracket.

  • > – matches the literal closing angle bracket.

So together, the pattern /\<[^>]+\>/ looks for any email address (or text) enclosed in < >.

Then, preg_replace replaces that entire match with a new string:

"<{$newEmail}>"

This ensures that whatever was originally between the brackets gets swapped out with the updated email address, while leaving the rest of the header (like the display name) unchanged.

Other Code Snippets

Change Permissions or Ownership of Files or Directories Recursively

Code Snippet | Linux

Sometimes when you are moving files from one host to another, you have to change the files owner or permissions so the web server can utilize it properly.

Read More
Find Files by Size

Code Snippet | Linux

Here is a Linux command line that searches for files that are over a certain size so that you can find where you might be able to free up some space. Useful to find error_logs that have run amok.

Read More
Import MySQL from Command Line

Code Snippet | Linux | MySQL

Here is a method to import a SQL file into a database via the Linux command line.

Read More
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram