• We just launched and are currently in beta. Join us as we build and grow the community.

How to Replace Newline with Space Using PHP

borngorilla234

Boss Fight Pro
B Rep
0
0
0
Rep
0
B Vouches
0
0
0
Vouches
0
Posts
68
Likes
113
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
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:

  1. $remove

    =

    array

    (

    "\n

    "

    ,

    "\r

    \n

    "

    ,

    "\r

    "

    )

    ;
  2. $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:

  1. $remove

    =

    array

    (

    "\n

    "

    ,

    "\r

    \n

    "

    ,

    "\r

    "

    ,

    "<p>"

    ,

    "</p>"

    ,

    "<h1>"

    ,

    "</h1>"

    )

    ;

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:

  1. $str

    =

    strip_tags

    (

    $str

    ,

    ‘<

    h1>

    ’)

    ;

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.

 

452,158

323,328

323,337

Top