What's the cross-platform regex to replace a line ending?
I've got a string like "foo\nbar"
, but depending on platform, that could become "开发者_StackOverflow社区foo\n\rbar"
, or whatever. I want to replace new lines with ", "
. Is there a nice (php) regex that'll do that for me?
Try the regular expression (?:\r\n|[\r\n])
:
preg_replace('/(?:\r\n|[\r\n])/', ', ', $str)
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
.
Wouldn't str_replace(array("\n", "\r"), "", $string)
work?
精彩评论