这可能看起来像是一个骗局,但请放心不是 - 我已经搜索了SO以及网络的其他部分来解决我的问题并最终找到相同的不足"解决方案"一遍又一遍.无论如何,这里是:
我将用户输入从textarea保存到MySQL数据库(在WordPress环境中,但我认为这对于这个问题不应该重要).稍后从数据库中检索它以显示给站点后端的管理员.当用户使用换行符提交文本时(即按Enter键)会出现问题.
示例字符串可能如下所示:
Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!
Greetings,
Bill
Run Code Online (Sandbox Code Playgroud)
字符串中没有行尾字符("\n","\ r"或类似字符).
我正在使用nl2br()它来生成HTML输出,但这还不够.结果是:
Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!<br />
<br />
Greetings,<br />
Bill
Run Code Online (Sandbox Code Playgroud)
据我所知,这是预期的nl2br()结果,因为插入标签并不应该首先替换换行符?
但是我需要的格式是这样的:
Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!<br /><br />Greetings,<br />Bill
Run Code Online (Sandbox Code Playgroud)
如果字符串中有EOL字符,例如"\n",我用其中任何一个str_replace()或者preg_replace()用它来完成它,但我不知道如果没有字符那么用什么针来提供这些函数首先.
我可以手动访问数据库中的相关字段,为每个换行符点击Backspace,以及我以后想要对字符串工作的内容.所以我知道我需要以上格式.
$string = "My text has so much whitespace
Plenty of spaces and tabs";
echo preg_replace("/\s\s+/", " ", $string);
Run Code Online (Sandbox Code Playgroud)
我阅读了PHP的文档并遵循preg_replace的教程,但是这段代码产生了
我的文字有很多空白,有很多空格和标签
我怎样才能把它变成:
我的文字有很多空白,有
很多空格和标签
我有这样的文本数据:
Learn More
Hide [x]
Colors
Fetching Colors description...
Show more topics
Art exhibitions
Fetching Art exhibitions description...
Abstract art
Fetching Abstract art description...
Representational art
Fetching Representational art description...
Run Code Online (Sandbox Code Playgroud)
我希望能够删除所有回车符,所以它变成这样:
Learn More Hide [x] Colors Fetching Colors description... Show more topics
Run Code Online (Sandbox Code Playgroud)
我如何在 PHP 中执行此操作?请注意,字符串可能是 UTF-8 字符串,我们需要考虑各种制表符、回车符和空格字符。(我正在思考编译器中使用的标记器算法,其中处理多个回车符和空格字符。)