Omar Abid
Omar Abid

Reputation: 15976

Replace all newline sequences with commas

I'm using str_replace and it's not working correctly. I have a text area, which input is sent with a form. When the data is received by the server, I want to change the new lines to ",".

$teams = $_GET["teams"];
$teams = str_replace("\n",",",$teams);
echo $teams;

Strangely, I receive the following result

Chelsea

,real


,Barcelona

instead of Chealsea,real,Barcelona.

What's wrong?

Upvotes: 2

Views: 5759

Answers (4)

Steve James
Steve James

Reputation: 31

I had the same issue but found a different answer so thought I would share in case it helps someone.

The problem I had was that I wanted to replace \n with <br/> for printing in HTML. The simple change I had to make was to escape the backslash in str_replace("\n","<br>",($text)) like this:

str_replace("\\n","<br>",($text))

Upvotes: 3

Matthew
Matthew

Reputation: 48284

I would trim the text and replace all consecutive CR/LF characters with a comma:

$text = preg_replace('/[\r\n]+/', ',', trim($text))

Upvotes: 4

Jim
Jim

Reputation: 18853

To expand on Waage's response, you could use an array to replace both sets of characters

$teams = str_replace(array("\r\n", "\n"),",",$teams);
echo $teams;

This should handle both items properly, as a single \n is valid and would not get caught if you were just replacing \r\n

Upvotes: 8

&#211;lafur Waage
&#211;lafur Waage

Reputation: 69981

Try replacing "\r\n" instead of just "\n"

Upvotes: 4

Related Questions