When Do I Use PHP_Eol Instead of \N and Vice-Versa? Ajax/Jquery Client Problem

When do I use PHP_EOL instead of \n and vice-versa ? Ajax/Jquery client problem

The constant PHP_EOL should generally be used for platform-specific output.

  • Mostly for file output really.
  • Actually the file functions already transform \n ←→ \r\n on Windows systems unless used in fopen(…, "wb") binary mode.

For file input you should prefer \n however. While most network protocols (HTTP) are supposed to use \r\n, that's not guaranteed.

  • Therefore it's best to break up on \n and remove any optional \r manually:

    $lines = array_map("rtrim", explode("\n", $content));

    Or use the file(…, FILE_IGNORE_NEW_LINES) function right away, to leave EOL handling to PHP or auto_detect_line_endings.

  • A more robust and terser alternative is using preg_split() and a regexp:

    $lines = preg_split("/\R/", $content);

    The \R placeholder detects any combination of \r + \n. So would be safest, and even work for Classic MacOS ≤ 9 text files (rarely seen in practice).

    Obligatory microoptimization note:

    While regex has a cost, it's surprisingly often speedier than manual loops and string postprocessing in PHP.

And there are a few classic examples where you should avoid PHP_EOL due to its platform-ambiguity:

  • Manual generation of network protocol payloads, such as HTTP over fsockopen().
  • For mail() and MIME construction (which really, you shouldn't do tediously yourself anyway).
  • File output, if you want to consistently write just Unix \n newlines regardless of environment.

So use a literal "\r\n" combination when not writing to files, but preparing data for a specific context that expects network linebreaks.

\n vs. PHP_EOL vs. br?

DOS, Unix, and Mac (pre-OS X and OS X) all use different characters or character combinations to represent "go to the next line."

  • DOS - Uses a CR+LF (that's ASCII 13 followed by an ASCII 10, or \r\n) to represent a new line.

  • Unix - Uses an LF (that's ASCII 10, or \n) to represent a new line.

  • Mac (pre-OS X) - Uses a CR (that's ASCII 13, or \r) to represent a new line.

  • Mac (OS X) - Like Unix, uses an LF to represent a new line.

Therefore, when to use each one depends on what you're going for. If you're writing for a specific platform without the intention of portability, use the character or character combination to break lines that matter to that platform. The purpose of PHP_EOL is to automatically choose the correct character for the platform, so that your new lines are platform-independent.

All of these appear as a single space within a browser as browsers collapse whitespace into a display space for display purposes (unless you're using <pre> as you mentioned, or CSS that changes the behavior of whitespace). This is where <br> comes in, as you've mentioned, which will convert these \n new line characters into <br> so that they provide line breaks in HTML display.

When do I use the PHP constant PHP_EOL?

Yes, PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.

Note that PHP_EOL represents the endline character for the current system. For instance, it will not find a Windows endline when executed on a unix-like system.

PHP_EOL does not work

PHP_EOL is platform-dependent. So it is different in windows and linux.

Moreover it seems you need a way to remove blank lines in a cross-platform way, but using PHP_EOL does not make the code cross-platform, since it depends on what newline-encoding the input file itself uses.

The best way to do this cross-platform is using a regex like /(\r\n)|\r|\n/ to split and/or replace black lines/newlines

$NEWLINE_RE = '/(\r\n)|\r|\n/'; // take care of all possible newline-encodings in input file
$var = preg_replace($NEWLINE_RE,'', $var);

Remove last comma from string with line breaks

This is what I ended up doing: I just added $Medio = rtrim($Medio,','.PHP_EOL) to remove last line break before removing the last comma as Alex Howansky pointed out.

$Medio=''; //variable to handle the result

$MedioPago='12345'; //variable with numbers given

$chars = str_split($MedioPago); //split the numbers

foreach($chars as $char)
{
if($char=='1')
{
$Medio.='"codigo": "01",'.PHP_EOL;
}
else if($char=='2')
{
$Medio.='"codigo": "02",'.PHP_EOL;
}
else if($char=='3')
{
$Medio.='"codigo": "03",'.PHP_EOL;
}
else if($char=='4')
{
$Medio.='"codigo": "04",'.PHP_EOL;
}
else if($char=='5')
{
$Medio.='"codigo": "05",'.PHP_EOL;
}
}

$Medio = rtrim($Medio,','.PHP_EOL);

substr_count not working with new lines?

You need to use double quotes for control characters:

var_dump(substr_count('df
d
fd
f
df', "\n"));

If variable contains word, show it and get line number

Example:

<?php

$desiredWord = 'apple';

$fileString = file_get_contents('asd.txt');

$lines = explode(PHP_EOL, $fileString);

$results = [];
foreach ($lines as $lineNumber => $line) {
if (strpos($line, $desiredWord) !== false) {
$results[] = ($lineNumber + 1) .":{$line}";
}
}

foreach ($results as $result) {
echo '<pre>' . print_r($result, true) . '</pre>';
}

Input file content:

apple
asdfsdf
vs
werwerwer
llll
hhheeheh
there is an apple on the tree
the tree does not fall far from it's apple

Output:

1:apple

7:there is an apple on the tree

8:the tree does not fall far from it's apple

You can go through on the lines with a foreach. The $lineNumber key contains the line index you are currently reading, and the $line is the string of the current line. The explode function will index your array from 0, so first line index will be 0 when you read it. That's why the + 1 in this line: $results[] = ($lineNumber + 1) .":{$line}";

With the if (strpos($line, $desiredWord) !== false) you are checking if you find the desired word in the given line. If you want only one result you can return here, but if you would like to collect all of the lines where the word can be found, then you store the found lines like this in the $results

Finally you can check the findings with the second foreach, or any other way - depends on your implementation.



Related Topics



Leave a reply



Submit