31

I've been working with phrases the past couple of days and the only problem I seem to be facing is stripping new lines in the html before printing it.

Anybody have any idea how to remove every new lines from HTML using PHP?

Sébastien
  • 11,376
  • 11
  • 52
  • 73
  • 1
    possible duplicate of [Remove new lines from string](http://stackoverflow.com/questions/3760816/remove-new-lines-from-string) – Gordon Jul 25 '11 at 20:25

2 Answers2

75
str_replace(array("\r", "\n"), '', $string)
ySgPjx
  • 9,953
  • 7
  • 57
  • 77
  • 5
    no need for "\r\n" if you're stripping them as individual characters. – Endophage Jul 20 '11 at 18:25
  • 3
    Would not work for me until I switched to single quotes: `str_replace(array('\r', '\n'), '', $string)` – chiliNUT Jan 31 '14 at 18:09
  • 1
    +1 for showing me a better way of doing `str_replace("text1","",str_replace("text2","",str_replace("text3","",str_replace("text4","",str_replace("text5","",$string)))))` or putting it in a loop. never knew the parsed needle could be the array – Memor-X Nov 05 '15 at 01:56
  • @chiliNUT I was stuck with the same double quotes problem and stumbled o your comment. Do you know the reason as to why the double quotes don't work? – Sushant Aug 01 '16 at 06:31
  • 1
    @sushant In answer to your question: single-quote strings are almost completely literal. '\n' is two characters: a slash followed by the letter 'n'. Double-quoted strings allow escaping of special characters like tabs and newlines. "\n" is one character, a newline. Which you want depends on what your string looks like, e.g. if it has newlines, or if it's, e.g. a JSON string which already has newlines escaped. – haz Nov 27 '18 at 02:11
2

the pt2ph8 answer didn't work for me until I have changed it a little bit as follows:

str_replace(array("\\r", "\\n"), '', $string);

You can see the different results in this demo:

http://phpfiddle.org/lite/code/g5s8-nt3i

user319730
  • 61
  • 1
  • 5
  • 1
    "\\r" is equivalent to '\r', which is different from "\r". The double quotes instruct PHP to parse \r \n \t and others as referring to special characters. The reason your example works is because your string simply contains the literal characters \ and r. – Trevor Gehman Mar 06 '20 at 19:31
  • More info on this here: https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double – Paul Feakins Jun 10 '21 at 12:01