Detect newline character

the next part is myfunction, which opens the file and places the pointer at the end. He then checks each $char character in reverse order until it finds a newline or carriage return character.

The problem is that it does not recognize these characters.

The function is as follows:

 while(count($results) < $limit && fseek($this->_pointer, $offset, SEEK_END) >= 0) { $char = fgetc($this->_pointer); if($char == '\n' || $char == '\r'){ print("YAY"); $offset --; $data = $this->explodeData(fgets($this->_pointer, 1024)); array_push($results, $this->formatRow($data)); } $offset--; } 

It never copes with print("YAY") , however, it successfully tests each character. The file he is reading definitely has newline characters in it. (The file was created by another function and "\n" was inserted into it, it displays inside it and successfully displays in my IDE as alternating lines).

Does anyone know why he cannot recognize these newlines?

+7
source share
3 answers

You use '\n' instead of "\n" .

 while(count($results) < $limit && fseek($this->_pointer, $offset, SEEK_END) >= 0) { $char = fgetc($this->_pointer); if($char == "\n" || $char == "\r"){ print("YAY"); $offset --; $data = $this->explodeData(fgets($this->_pointer, 1024)); array_push($results, $this->formatRow($data)); } $offset--; } "\n" == LF character '\n' == '\n'; // Variables are effected also $var = 'foo'; print "$var"; // prints 'foo'; print '$var'; // prints '$var'; 
+10
source

To make your code platform agnostic, it is better to have your if conditions as follows:

 if($char == PHP_EOL) { print("YAY"); // your rest of the code } 

Thanks to the comment by @ FΓ©lix Gagnon-Grenier below.

PHP_EOL may not work with strings that come from other systems. PHP_EOL represents the end character of the current system.

To have it detect all types of newline characters, including newline characters in Unicode, use \R :

 preg_match('/\R/', $str); 

\R equivalent (?>\r\n|\n|\r|\f|\x0b|\x85|\x{2028}|\x{2029})

Demo code

+14
source

use double quotes instead of single quotes around "\ n" and "\ r"

I had a similar nightmare some time ago, until I realized that php does not use escape characters unless they are in double quotes.

+2
source

All Articles