This is a short guide on how to use newlines and carriage return characters from text using PHP. In certain cases, you may want to prevent your users from using these characters, as they can interfere with the layout of your web pages.
Firstly, you need to realize that newlines “\n” and carriage return characters “\r” are usually invisible. i.e. They will not show up when you print the text out onto your web page. Nor will they appear when you are looking at the text column in your database.
Removing newlines using str_replace.
The first solution is to use the PHP function str_replace like so:
<?php //An example piece of text that //contains (invisible) newline characters. $text = "Hello this is a test "; //Before echo nl2br($text); //Replace the newline and carriage return characters //using str_replace. $text = str_replace(array("\n", "\r"), '', $text); //After echo nl2br($text);
If you run the code above, you’ll see that the str_replace function has removed all instances of “\n” and “\r”. All we had to do was supply the function with an array of the characters that we wanted to replace.
This solution is preferred over using regex, as it is faster and less CPU intensive.
Remove newlines using regex.
If you’re adamant about removing these characters with regex, then you can use the following PHP snippet instead:
//Replace the newline and carriage return characters //using regex and preg_replace. $text = preg_replace("/\r|\n/", "", $text);
Both of them will lead to the same result – It’s just that str_replace is more efficient.