Capturing linebreaks (newline,linefeed) characters in a textarea

和自甴很熟 提交于 2019-11-29 06:07:55

问题


I have a form with a <textarea> and I want to capture any line breaks in that textarea on the server-side, and replace them with a <br/>.

Is that possible?

I tried setting white-space:pre on the textarea's CSS, but it's still not enough.


回答1:


Have a look at the nl2br() function. It should do exactly what you want.




回答2:


The nl2br() function exists to do exactly this:

However, this function adds br tags but does not actually remove the new lines - this usually isn't an issue, but if you want to completely strip them and catch carriage returns as well, you should use a str_replace or preg_replace

I think str_replace would be slightly faster but I have not benchmarked;

$val = str_replace( array("\n","\r","\r\n"), '<br />', $val );

or

$val = preg_replace( "#\n|\r|\r\n#", '<br />', $val );



回答3:


If you're going to use str_replace or preg_replace, you should probably place the "\r\n" at the beginning of the array, otherwise a \r\n sequence will be translated into two <br/> tags (since the \r will be matched, and then the \n will be matched).

eg:

$val = str_replace( array("\r\n", "\n","\r"), '<br />', $val );

or

$val = preg_replace( "#\r\n|\n|\r#", '<br />', $val );



回答4:


For those wanting an answer that does not rely on nl2br():

$newList = ereg_replace( "\n",'|', $_POST['theTextareaContents']);

or (in this case):

$newList = ereg_replace( "\n",'<br/>', $_POST['theTextareaContents']);

PHP Side: from Textarea string to PHP string

$newList = ereg_replace( "\n",'|', $_POST['theTextareaContents']);

PHP Side: PHP string back to TextArea string:

$list = str_replace('|', '&#13;&#10;', $r['db_field_name']);


来源:https://stackoverflow.com/questions/289159/capturing-linebreaks-newline-linefeed-characters-in-a-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!