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

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?

php


Solution 1:[1]

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

Solution 2:[2]

The most reliable way to detect new line in the text that may come from different operating systems is:

preg_match('/\R/', $string)

\R comes from PCRE and it is the same as: (?>\r\n|\n|\r|\f|\x0b|\x85|\x{2028}|\x{2029})

The suggested answer to check PHP_EOL

if(strstr($string, PHP_EOL)) {

will not work if you are for example on Windows sytem and checking file created in Unix system.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mouna Cheikhna
Solution 2 sprutex