Adding line breaks within a string in PHP

This is something that has been on my “unsure” list for a long time. Partly because I haven’t really done my research on it and because, well, I just don’t require this very often. Finally, today I had a situation come up when I needed to ensure that the notes I am adding into the database are broken up with a line break between each note.

I know that there are these “\n” and “\r” or something like that but any time I’ve tried using them in the past it never worked consistently.

So today I decided to, once and for all, get to the bottom of this.

Solution

What I was doing wrong is not always placing the string in double-quotes. Sometimes I had it in single quotes and this is when \n did not work.

$string = "this is my string\n";
$string .= "and this is the next line";

echo $string;

Result:
this is my string
and this is the next line

Make sure to use double-quotes (“) not single (‘).

WHEN PASSING STRINGS AROUND IN PHP VARIABLES OR ARRAYS

When you pass this string around from variable to variable or array, they get passed in single quotes, so the \n breaks. To solve that you just need to reset this at the very last pass, like this:


$str = str_replace('\n', "\n", $str);

This will reset the line breaks back in double-quotes. :)

Author: Valik Rudd

Valik (Valiik) Rudd is an Internet entrepreneur. He develops new online businesses and creates new websites. His other passion is writing about the those things. Web Design Ideas blog is the outlet through which his ideas and web design tricks and tips get recorded and shared with others.

1 thought on “Adding line breaks within a string in PHP”

Leave a Reply

Your email address will not be published. Required fields are marked *