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?
views:
54answers:
3I 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
2010-01-29 23:26:46
hmm... no, that won't get the \r only case. (Does that exist?)
sprugman
2010-01-29 23:27:22
just replace the 2nd argument with `", "`
Chacha102
2010-01-29 23:34:36
no, then I'd get `foo, , bar` for the \n\r case. (unless I'm reading the docs wrong. :)
sprugman
2010-01-29 23:35:14
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
2010-01-29 23:43:05
`\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
2010-01-30 02:24:54
+3
A:
Try the regular expression (?:\r\n|[\r\n])
:
preg_replace('/(?:\r\n|[\r\n])/', ', ', $str)
Gumbo
2010-01-29 23:21:34
Nice! I've always used `\r?\n|\r` or `\n|\r\n?`, but I think this is clearer.
Alan Moore
2010-01-30 04:18:54
+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
2010-01-30 00:34:39