tags:

views:

54

answers:

3

I've got a string like "foo\nbar", but depending on platform, that could become "foo\n\rbar", or whatever. I want to replace new lines with ", ". Is there a nice (php) regex that'll do that for me?

A: 

Wouldn't str_replace(array("\n", "\r"), "", $string) work?

Chacha102
I forgot that str_replace will take arrays. However, yours won't replace with commas. For that I think it has to be `str_replace(array("\n", "\r"), array(', ', ''), $string)`
sprugman
hmm... no, that won't get the \r only case. (Does that exist?)
sprugman
just replace the 2nd argument with `", "`
Chacha102
no, then I'd get `foo, , bar` for the \n\r case. (unless I'm reading the docs wrong. :)
sprugman
Actually, yes, you are right. If both were there, you would get it twice. You'd probably want to put the comma in place of the newline, since it is present on both Operating Systems. I don't believe that there is a return-only case however.
Chacha102
`\n\r` *is* two line separators. If you're thinking of the Windows/DOS/network line separator, that's `\r\n`. `\n\r` is a Unix/Linux/OSX line separator (`\n`) followed by pre-OSX Mac line separator (`\r`--so yes, there is a return-only case).
Alan Moore
+3  A: 

Try the regular expression (?:\r\n|[\r\n]):

preg_replace('/(?:\r\n|[\r\n])/', ', ', $str)
Gumbo
+1, Nice one. I would only add a `+` at the end of the regex.
Alix Axel
Nice! I've always used `\r?\n|\r` or `\n|\r\n?`, but I think this is clearer.
Alan Moore
+1  A: 

You dont want to use a Regex for a simple replacement like this. Regular string replacement functions are usually much faster. For the line break, you can use the OS aware constant PHP_EOL, e.g.

str_replace(PHP_EOL, ', ', $someString);

On Windows, this will replace \r\n. On Mac \r and on all other systems \n.

Gordon
That is only the current machine, what if it is coming from another machine?
Chacha102
@Chacha102 if the other machine runs another OS, then PHP_EOL won't do. Still, I find it a noteworthy option.
Gordon