如何用单个换行符替换包含任意换行符和空格序列的字符串
我正在尝试构建一个 PHP 字符串替换/正则表达式函数,该函数接受具有任意换行符和空格序列的字符串,并将其替换为单个换行符。
这可能吗?如果可以,该怎么做?
I'm trying to construct a PHP string replacement / regex function that takes a string with any sequence of linefeeds and spaces and replaces it with a single line feed.
Is this possible and, if so, how would it be done ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试:
它会查找单个 CR 或 LF 来检测 Unix、Windows 和旧 Mac 换行符。之后任何空白(空格、制表符、CR、LF)都将被删除。
\s*
以忽略前一行上的空格。\s*
也可以是[\r\n ]*
。另请参阅 https://stackoverflow.com/questions/ 89718/is-there-anything-like-regexbuddy-in-the-open-source-world 如果你想改进这个正则表达式。
You could try:
It will look out for a single CR or LF to detect Unix, Windows and old Mac line breaks. And after that any whitespace (space, tab, CR, LF) will be removed.
\s*
to ignore spaces on the preceding line.\s*
could also be[\r\n ]*
if you want to keep \tabs.See also https://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world if you want to refine this regex.
如果空格/换行符可以以任何顺序出现并且来自任何潜在的操作系统,那么这将是一种霰弹枪方法:
它将查找一个或多个空格(\s)、换行符(\n)和回车符(\ r) 字符并用换行符替换它们。
If the spaces/breaks can come in any sequence and from any potential OS, then this would be a shotgun approach:
It'll look for one-or-more whitespace (\s), newline (\n) and carriage return (\r) characters and replace them with a newline.
试试这个:
http://www.regular-expressions.info/tutorial.html
太棒了源材料!
Try this:
http://www.regular-expressions.info/tutorial.html
Great source material!