问题描述
这似乎是一个愚蠢的事情,但请放心,事实并非如此 - 我已经在搜索以及网络的其他部分寻找解决问题的答案,最终找到了同样不足的解决方案过度。无论如何,这里是:我将一个textarea的用户输入保存到一个MySQL数据库中(在WordPress环境中,但这对这个问题应该没有关系,我相信)。它稍后从数据库中检索,并显示给站点后端的管理员。问题发生在用户使用换行符提交文本(即按Enter键)时。
示例字符串可能如下所示:
亲爱的朋友,我只是想这么好。你们好吗?我很好谢谢!
问候,
比尔
字符(\ n,\r等)。
我正在使用 nl2br()
来生成HTML输出,但这还不够。结果是:
亲爱的朋友们,我只是想这么好。你们好吗?我很好,谢谢!< br />
< br />
问候,< br />
Bill
据我所知,其中预期的 nl2br()
result,因为插入标签并且不应该首先替换换行符?
然而,我需要的格式是这样的:
亲爱的朋友们,我只是想这么好。你们好吗?我很好,谢谢!< br />>< br />问候,< br />
如果字符串中有EOL字符,例如\ n,我会用 str_replace()
或 preg_replace()
并完成它,但如果首先没有字符,我不知道用什么针喂这些函数。
我可以手动访问数据库中的相关字段,为每个换行符点击Backspace,以及之后我想要对字符串进行操作。所以我知道我需要上面的格式。
解决方案你应该能够用一个preg替换它,回报。代码是:
preg_replace(/ \r | \\\
/,,$ yourString);
尽管 \\\
字符是没有出现,如果你得到回车,那里有一个看不见的角色。 preg替换应该抓住并修复这些。
This might appear to be a dupe, but rest assured it isn't - I have searched both SO as well as the rest of the web for an answer to my problem and ended up finding the same insufficient "solutions" over and over. Anyhow, here it goes:
I'm saving user input from a textarea to a MySQL database (within a WordPress environment, but that ought not to matter to this problem, I believe). It is later retrieved from the DB to be shown to Admins in the backend of the site. The problem occurs when users submit text with line breaks (i.e. hit the Enter key).
A sample string might look like this:
Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!
Greetings,
Bill
There are no end of line characters ("\n", "\r", or the like) in the string.
I am using nl2br()
on it to generate HTML output, but that's not enough. The result then is:
Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!<br />
<br />
Greetings,<br />
Bill
Which, as far as I understand it, is the expected nl2br()
result, as that inserts the tags and isn't supposed to replace the line-breaks in the first place?
However the format I need would be this:
Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!<br /><br />Greetings,<br />Bill
If the string had EOL characters such as "\n" in it, I'd hit it with either str_replace()
or preg_replace()
and be done with it, but I have no clue what needle to feed either of those functions if there ain't no characters there in the first place.
I can manually access the relevant field in the DB, hit Backspace for every linebreak and what I later on want to do with the string works. So I know I need the above format.
解决方案 You should be able to replace it with a preg that removes all newlines and carriage returns. The code is:
preg_replace( "/\r|\n/", "", $yourString );
Even though the \n
characters are not appearing, if you are getting carriage returns there is an invisible character there. The preg replace should grab and fix those.
这篇关于如何从字符串中删除换行符(无字符!)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!