替换多个换行符、制表符和空格
我想用一个换行符替换多个换行符,用一个空格替换多个空格。
我尝试了 preg_replace("/\n\n+/", "\n", $text);
但失败了!
我还在 $text 上完成这项工作以进行格式化。
$text = wordwrap($text, 120, '<br/>', true);
$text = nl2br($text);
$text 是从 BLOG 用户那里获取的大文本,为了更好的格式化,我使用了 wordwrap。
I want to replace multiple newline characters with one newline character, and multiple spaces with a single space.
I tried preg_replace("/\n\n+/", "\n", $text);
and failed!
I also do this job on the $text for formatting.
$text = wordwrap($text, 120, '<br/>', true);
$text = nl2br($text);
$text is a large text taken from user for BLOG, and for a better formatting I use wordwrap.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
理论上,正则表达式确实有效,但问题是并非所有操作系统和浏览器仅在字符串末尾发送 \n 。许多人还会发送\r。
尝试:
我简化了这一点:
并解决某些仅发送 \r 的问题:
根据您的更新:
In theory, you regular expression does work, but the problem is that not all operating system and browsers send only \n at the end of string. Many will also send a \r.
Try:
I've simplified this one:
And to address the problem of some sending \r only:
Based on your update:
它在这里找到:用段落标签替换两行
关于 转义序列:
It was found here: Replacing two new lines with paragraph tags
PHP documentation about Escape sequences:
这就是答案,正如我理解的问题:
这是我用来将新行转换为 HTML 换行符和段落元素的实际函数:
This is the answer, as I understand the question:
This is the actual function that I use to convert new lines to HTML line break and paragraph elements:
您需要多行修饰符来匹配多行:
另外,在您的示例中,您似乎将 2 个以上换行符替换为 2 个换行符,这不是您的问题所表明的。
You need the multiline modifier to match multiple lines:
Also in your example you seem to be replacing 2+ newlines with exactly 2, which isn't what your question indicates.
我尝试了以上所有方法,但对我来说没有用。然后我创建了一些很长的方法来解决这个问题......
之前:
之后:
它对我有用......我写在这里是因为,如果有人像我一样来这里寻找答案。
I tried all of above, but it didn't work for me. Then I created some long way to resolve that issue...
Before :
After :
And it's worked for me.. I wrote here because, if somebody came here to find answer like me.
我建议这样:
这将处理所有 Unicode 换行符。
I would suggest something like this:
This will take care of all the Unicode newline characters.
如果您只想用单个选项卡替换多个选项卡,请使用以下代码。
If you just want to replace multiple tabs with a single tab, use the following code.
试试这个:
Try this:
替换字符串或文档的头部和结尾!
Replace the head and the end of string or document!
我在 PHP 中处理过 strip_tags 函数,遇到了一些问题,例如:在换行之后出现一个带有一些空格的新行,然后连续出现一个新的换行符......等等。没有任何规则:(。
这是我处理 strip_tags 的解决方案
将多个空格替换为一个,将多个换行符替换为单个换行符
关键字是 (*) 和 (**)。
I have dealt with strip_tags function in PHP and had some problems like: after having a linebreak then appear a new line with some spaces and then a new linebreak appear continuously ...etc. without any rule :(.
This is my solution for dealing with strip_tags
Replace multiple spaces to one, multiple linebreaks to single linebreak
Keywords are (*) and (**).