php 如何检测字符串中是否有换行符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9437121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect if a string has a new line break in it?
提问by TK123
This doesn't work:
这不起作用:
$string = 'Hello
world';
if(strpos($string, '\n')) {
echo 'New line break found';
}
else {
echo 'not found';
}
Obviously because the string doesn't have the "\n" character in it. But how else can I check to see if there is a line break that is the result of the user pressing enter in a form field?
显然是因为字符串中没有“\n”字符。但是我还能如何检查是否有换行符是用户在表单字段中按下 Enter 的结果?
回答by rdlowrey
Your existing test doesn't work because you don't use double-quotes around your line break character ('\n'
). Change it to:
您现有的测试不起作用,因为您没有在换行符 ( '\n'
)周围使用双引号。将其更改为:
if(strstr($string, "\n")) {
if(strstr($string, "\n")) {
Or, if you want cross-operating system compatibility:
或者,如果您想要跨操作系统兼容性:
if(strstr($string, PHP_EOL)) {
if(strstr($string, PHP_EOL)) {
Also note that strpos
will return 0 and your statement will evaluate to FALSE if the first character is \n
, so strstr
is a better choice. Alternatively you could change the strpos
usage to:
另请注意,strpos
如果第一个字符是\n
,则将返回 0 并且您的语句将评估为 FALSE ,因此strstr
是更好的选择。或者,您可以将strpos
用法更改为:
if(strpos($string, "\n") !== FALSE) {
echo 'New line break found';
}
else {
echo 'not found';
}
回答by Mouna Cheikhna
line break is \r\n
on windows and on UNIX machines it is \n
.
so its search for PHP_EOL
instead of "\n" for cross-OS compatibility, or search for both "\r\n" and "\n".
换行符\r\n
在 Windows 和 UNIX 机器上是\n
。所以它搜索PHP_EOL
而不是“\n”以获得跨操作系统兼容性,或者搜索“\r\n”和“\n”。