PHP Tips: How to convert underscores to spaces in emailed contact forms

I was recently building a PHP contact form and ran into the issue where the field names I was using in my HTML form which we were more than one word long (i.e.: “First Name”) were being emailed with underscores in place of the spaces (i.e.: “First_Name”). The PHP file I was processing my form with was replacing the spaces with underscores. Which was necessary for processing the form, BUT – I needed to convert those underscores back to spaces when the contact form data was emailed for usability purposes.

Here is the simple line of code that I added to my PHP file:

$msg = str_replace("_"," ", $msg);

Where $msg was part of my mail function:

 mail($to, $subject, $msg, $headers)

And had already been defined:

  $msg = "User message: \n\n";
          foreach($this->fields as $key => $field)
                $msg .= "$key:  $field \n";

I added the first line of code (which used the str_replace function) right after the code which defined $msg.

You will want to replace the variable $msg in the code above with the name of the variable you are using for the body of the email in your mail function.