如何以最聪明的方式替换 PHP 中的不同换行符样式?
我的文本可能有不同的换行样式。 我想用相同的换行符替换所有换行符 '\r\n', '\n','\r' (在本例中为 \r\n )。
最快的方法是什么?我当前的解决方案看起来像这样,这很糟糕:
$sNicetext = str_replace("\r\n",'%%%%somthing%%%%', $sNicetext);
$sNicetext = str_replace(array("\r","\n"),array("\r\n","\r\n"), $sNicetext);
$sNicetext = str_replace('%%%%somthing%%%%',"\r\n", $sNicetext);
问题是您无法通过一次替换来完成此操作,因为 \r\n 将被复制到 \r\n\r\n 。
感谢您的帮助!
I have a text which might have different newline styles.
I want to replace all newlines '\r\n', '\n','\r' with the same newline (in this case \r\n ).
What's the fastest way to do this? My current solution looks like this which is way sucky:
$sNicetext = str_replace("\r\n",'%%%%somthing%%%%', $sNicetext);
$sNicetext = str_replace(array("\r","\n"),array("\r\n","\r\n"), $sNicetext);
$sNicetext = str_replace('%%%%somthing%%%%',"\r\n", $sNicetext);
Problem is that you can't do this with one replace because the \r\n will be duplicated to \r\n\r\n .
Thank you for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
也有效
also works
如果您不想替换所有 Unicode 换行符,而只想替换 CRLF 样式的换行符,请使用:
\R
匹配这些换行符,u
是将输入字符串视为 UTF 的修饰符-8。来自 PCRE 文档:
和
If you don't want to replace all Unicode newlines but only CRLF style ones, use:
\R
matches these newlines,u
is a modifier to treat the input string as UTF-8.From the PCRE docs:
and
为了标准化换行符,我总是使用:
它将旧的 Mac (
\r
) 和 Windows (\r\n
) 换行符替换为 Unix 等效项 (\n )。
我更喜欢使用
\n
,因为它只需要一个字节而不是两个字节,但您可以轻松地将其更改为\r\n
。To normalize newlines I always use:
It replaces the old Mac (
\r
) and the Windows (\r\n
) newlines with the Unix equivalent (\n
).I preffer using
\n
because it only takes one byte instead of two, but you can easily change it to\r\n
.怎么样
How about
我认为转换为 CRLF 的最聪明/最简单的方法是:
仅转换为 LF:
它比正则表达式容易得多。
i think the smartest/simplest way to convert to CRLF is:
to convert to LF only:
it's much more easier than regular expressions.