-1

I've encountered some strange behavior with PHP. I have a string of text from a <textarea/> input and it seems that:

$text = str_replace(array("\r\n", "\r", "\n"), null, $text);

successfully removes the newlines, whereas

$text = str_replace("\n", " ", $text)
$text = str_replace("\r\n", " ", $text)
$text = str_replace("\r", " ", $text)

EDIT: the three str_replace calls above are for \n, \r\n, and \r

does NOT successfully remove newlines. I even tried adding:

$text = str_replace(PHP_EOL, " ", $text);

but it doesn't fix the problem. I know I'm replacing the newlines with a space instead of null, but I would expect this to also work. After doing the 3-4 str_replace() calls, if I:

echo nl2br($text);

it does in fact find some remaining newline characters.

Any ideas?

vette982
  • 4,782
  • 8
  • 34
  • 41
  • 2
    You have a line repeated 3 times... did you mean `\r\n` in the first one, `\r` in the second one and \n in the `3rd` one? – Francisco Presencia Apr 12 '12 at 17:19
  • Also, you are replacing with `null` in the first method, but with a single space in the others. Is that on purpose? – jb. Apr 12 '12 at 17:21
  • Frank, yes it's a huge typo, sorry! jb, yes that is intentional, but I would expect each to behave similarly in actually removing the newlines. – vette982 Apr 12 '12 at 18:29

2 Answers2

3

Text coming from an textarea ALWAYS has \r\n linebreaks.

So you should just do $text = str_replace("\r\n", '', $text);

See the spec for more info.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
  • 1
    `Text coming from an textarea ALWAYS has \r\n linebreaks` - Is that true? I'd always assumed it used the type of line ending used by the OS... Well, you learn something every day. And passing `null` as the replacement is identical to passing `''`, so you might as well just do that. – DaveRandom Apr 12 '12 at 17:19
  • Lemme get the spec for you. 1 sec pls – PeeHaa Apr 12 '12 at 17:19
  • @DaveRandom Never too old to learn ;) And it was by no means trouble – PeeHaa Apr 12 '12 at 17:23
  • 1
    If text in the textarea was not standardized, it would follow the OS conventions of the *user's* computer, not of the server. – alexis Apr 12 '12 at 17:26
  • Given the edit I made above (huge typo, sorry everyone!), $text = str_replace("\r\n", '', $text); didn't actually work. – vette982 Apr 12 '12 at 18:28
  • Extremely relevant: http://stackoverflow.com/questions/6324167/do-browsers-send-r-n-or-n-or-does-it-depend-on-the-browser – thirtydot Apr 12 '12 at 18:30
1

You should use:

$text = str_replace("\r\n", " ", $text)
$text = str_replace("\r", " ", $text)
$text = str_replace("\n", " ", $text)

or

$text = str_replace("\r\n", null, $text)
$text = str_replace("\r", null, $text)
$text = str_replace("\n", null, $text)
sarwar026
  • 3,821
  • 3
  • 26
  • 37