How to Replace Newline with Space Using PHP

Sometimes you need to replace newline (i.e. \r\n) with space. While I am trying to do this in my website I wonder why str_replace function doesn’t work.

Example:

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

While the above code is correct I found out that not all instances of my article’s content uses the PHP escape code to insert a newline.

Now, I figured it out after copying and pasting the content of the article to Macromedia Dreamweaver. I found that the article is using an HTML tag to process a newline. The code above will still work if you add more tag into it.

Example:

$remove = array("\n", "\r\n", "\r", "

", "

", "

", "

");

But what if the tag is not defined in the array? So, in order to solve this problem I use the strip_tags function which will automatically remove all the tags within a string.

The best part here is that you can optionally add a tag to keep in your string.

Example:

$str = strip_tags ($str, ‘

’);

This function is also very useful in comments form. Whether they put an HTML tag or not you can assure that all tags are being filtered before they are process and displayed in browser.

Comments

Submitted byAnonymous (not verified)on Wed, 01/20/2010 - 18:03

tnx a lot
Submitted byAnonymous (not verified)on Thu, 03/17/2011 - 16:38

Thanks. Simple and great code.

Add new comment