Open any text file and click on the pilcrow (¶) button. Notepad++ will show all of the characters with newline characters in either the CR and LF format. If it is a Windows EOL encoded file, the newline characters of CR LF will appear (\r\n).
PHP_EOL represents the endline character for the current system (eg \n on unixes) however if you are treating strings from a windoes system (\r\n) they won't be rexognised as endlines. PHP_EOL is "The correct 'End Of Line' symbol for this platform".
Create a string containing line breaksInserting a newline code \n , \r\n into a string will result in a line break at that location. On Unix, including Mac, \n (LF) is often used, and on Windows, \r\n (CR + LF) is often used as a newline code.
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';
}
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With