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?
我有一个像“foo \ nbar”这样的字符串,但是根据平台,这可能变成“foo \ n \ rbar”,或者其他什么。我想用“,”替换新行。是否有一个很好的(PHP)正则表达式,我会这样做?
3 个解决方案
#1
5
Try the regular expression (?:\r\n|[\r\n])
:
试试正则表达式(?:\ r \ n | [\ r \ n]):
preg_replace('/(?:\r\n|[\r\n])/', ', ', $str)
#2
2
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.
你不想使用正则表达式进行这样的简单替换。常规字符串替换功能通常要快得多。对于换行符,您可以使用OS感知常量PHP_EOL,例如
str_replace(PHP_EOL, ', ', $someString);
On Windows, this will replace \r\n
. On Mac \r
and on all other systems \n
.
在Windows上,这将替换\ r \ n。在Mac \ n \ n和所有其他系统上\ n。
#3
-1
Wouldn't str_replace(array("\n", "\r"), "", $string)
work?
不会str_replace(array(“\ n”,“\ r”),“”,$ string)工作吗?
#1
5
Try the regular expression (?:\r\n|[\r\n])
:
试试正则表达式(?:\ r \ n | [\ r \ n]):
preg_replace('/(?:\r\n|[\r\n])/', ', ', $str)
#2
2
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.
你不想使用正则表达式进行这样的简单替换。常规字符串替换功能通常要快得多。对于换行符,您可以使用OS感知常量PHP_EOL,例如
str_replace(PHP_EOL, ', ', $someString);
On Windows, this will replace \r\n
. On Mac \r
and on all other systems \n
.
在Windows上,这将替换\ r \ n。在Mac \ n \ n和所有其他系统上\ n。
#3
-1
Wouldn't str_replace(array("\n", "\r"), "", $string)
work?
不会str_replace(array(“\ n”,“\ r”),“”,$ string)工作吗?