开发者

newline question

I want to detect a carriage return or a newline character when a user enters data into a textarea. What is the best way to handle this? I've tried str_replace with escape characters but carriage returns and newlines are not detected.


OK, say I type th开发者_如何学Ce following into a textarea:

The summer was hot this year
but next year is supposed to be cooler.

I want to detect the CRs. In this case, there is one.


Newlines could be \r, \r\n, or \n, depending on the client.

$input = preg_replace('/\r\n?/',"\n",$input)

will standardize all of your newlines to "\n" regardless of where they came from.


You can do it like this with str_replace:

function replace_newline($string) {
  return (string)str_replace(array("\r", "\r\n", "\n"), '', $string);
}


There are several ways how new line is stored. Some systems use only "\n" some "\r" and some both "\r\n". You need to check for both "\r" and "\n"


Try the following. It's always worked a charm for me.

You need to replace \n AND \r, it's because a linux system and a windows system use different characters for newlines.

$input = str_replace(array("\n","\r"),'',$input);


Or check for chr(10) and replace on that


Have you tried preg_replace because that can be used for regex replacements and then you can replace using \n or \r or any combination you require although I believe str_replace should also work fine.


function replace_newlines($string) {
    return preg_replace('/\r\n|\r|\n/', '', $string);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜