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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:49:18  来源:igfitidea点击:

How to detect if a string has a new line break in it?

php

提问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 strposwill return 0 and your statement will evaluate to FALSE if the first character is \n, so strstris a better choice. Alternatively you could change the strposusage 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\non windows and on UNIX machines it is \n. so its search for PHP_EOLinstead 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”。