Home » Php » php – How to detect if a string has a new line break in it?

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

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&Answers:

Your existing test doesn’t work because you don’t use double-quotes around your line break character ('\n'). Change it to:

if(strstr($string, "\n")) {

Or, if you want cross-operating system compatibility:

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:

if(strpos($string, "\n") !== FALSE) {
  echo 'New line break found';
}
else {
  echo 'not found';
}

Answer:

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”.