In case you haven’t noticed, with most PHP form processors, if a user fills out a textarea within your form using paragraphs or line breaks, the formatting of the paragraphs and line breaks are stripped away from your delivered e-mail contents.
In this example, we will use the PHP nl2br() function to fix this, displaying your form e-mail contents precisely as the user provided them.
What Does the PHP nl2br Function Do?
It’s straightforward really, the nl2br() function is used to insert HTML line breaks before any new lines within a string. In this case, we want to use the PHP nl2br() function and insert our form textarea field contents within that function to achieve paragraphs and line breaks when the form is submitted to us as an e-mail.
Let’s Look At Some Basic Code To Receive Your Textarea Field With The nl2br() function Included
The first order of business is our standard HTML textarea form field; for this example, we will name it “details” and this is how our form HTML will look:
<textarea placeholder="Details..." name="details" required></textarea>
Now, within your PHP script to process your form to e-mail, we will need to grab the textarea contents, which will look like:
$details = $_REQUEST['details'];
Next, for the contents of $details to be delivered with paragraphs and line breaks included based on how the user filled out the textarea we will need to add our nl2br() function. With the PHP from the above code included, this will look like:
$details = $_REQUEST['details'];$details = nl2br($details);
There you have it; the above code places your textarea field contents within the PHP nl2br() function, which will now save the line breaks that your user has entered into the specific textarea.