Php get end of line

End of Line/Newline Problem

Assuming that PHP_EOL directive and the new line «\n» do the same thing, neither are working. I’ve recently updated to PHP5 after a long hiatus from PHP altogether. I have tried putting the newline character in single and double quotes, but to no avail. Anyone have any suggestions? Thanks in advance.
-Woobag edit — forgot to say that the characters throw no errors or exceptions, but simply do nothing, as if they were not there

  • 12 Contributors
  • 14 Replies
  • 2K Views
  • 4 Years Discussion Span
  • Latest Post 10 Years Ago Latest Post by EvolutionFallen

Well the \n isn’t parsed for single quotes but it is for double quotes. Also, I’m not sure where you’re trying to use it but if you are just outputting to an HTML page then it wont display the newline because whitespace characters(unless preempted with a ) tag are ignored. …

Because in HTML whitespace characters (newline, space, tab) are ignored with rendering the page.

hi woobag,
i think u can use «
» instead of «\n»

edit — I tried wrapping the PHP code in tags and that did the trick, still trying to understand why it does not work without them.

As other people have pointed out, the reason this doesn’t work without a tag is that HTML ignores normal whitespace characters.

All 14 Replies

Well the \n isn’t parsed for single quotes but it is for double quotes. Also, I’m not sure where you’re trying to use it but if you are just outputting to an HTML page then it wont display the newline because whitespace characters(unless preempted with a

) tag are ignored. You can use the nltobr(string) function to convert them however
 'bar', 'baz', 'bat' => 2); function printArray($array) < reset($array); while(key($array) !== null) < echo key($array) .": " . current($array) . "\n"; next($array); >> printArray($array); echo "This is a" . PHP_EOL . " new line."; ?>

Both are not working to produce new lines. Sorry i didn’t post this first. edit — I tried wrapping the PHP code in

tags and that did the trick, still trying to understand why it does not work without them.

edit — I tried wrapping the PHP code in tags and that did the trick, still trying to understand why it does not work without them.

As other people have pointed out, the reason this doesn’t work without a

tag is that HTML ignores normal whitespace characters. The reason it does work with a 
tag is that that is what 
tags are designed for. The text inside of a 
tag will be displayed with all white space intact - in your case with a newline character. As was suggested before, use a 
tag instead of an '\n' if you want to create a line break in your HTML output. However, the '\n' still has a function and it is still doing something. If you view the HTML source for the output of your script, you should notice that the newline is observed. So, if you're echo-ing large amounts of HTML, it can be a very good idea to include newline characters in there. That way your source code is still readable and not just one long jumbled line. - Walkere

Источник

Using end of line in PHP echo string

Solution 3: try this normally you can use and at time of file handling Solution 4: If you want to print text containing eol's in html, give nl2br a shot It will add HTML line breaks before all eols. Solution 2: If You can't split by new line.

Using end of line in PHP echo string

I am trying to write a PHP script that echo s a string, but it doesn't recognize the end of line function in there.

echo "thank you \n " echo "for coming over" 

The \n is ignored and it prints the whole line as thank you for coming over .

I got the same result for the following to:

echo "thank you " . PHP_EOL.; echo "for coming over" . PHP_EOL.; 

There are different ways to solve that:

Using Pre-formatted text

echo '
'; // pre-formatted text, \n should work echo "thank you \n "; echo "for coming over"; echo '

';

Changing the content type

header('Content-Type: text/plain'); echo "thank you \n "; echo "for coming over"; 

You browser will now properly read the output as text.

Using the HTML break element

echo "thank you 
\n "; echo "for coming over";

So output always depends on what you want to output. Is it text? Is it HTML? Is it some text within HTML? Depending on what you need you should take care on the format and formatting.

If you are doing this in a browser, replace \n with
. The file line breaks are not rendered in an HTML page, unless specified via CSS or if they're enclosed in certain tags. You could also optionally change the file type to text/plain , but I don't think that would be desired.

try this normally you can use

 echo "thank you 
"; echo "for coming over
";

and at time of file handling

echo "thank you ".PHP_EOL.""; echo "for coming over".PHP_EOL.""; 

If you want to print text containing eol's in html, give nl2br a shot

$str = "thank you \n "; $str .= "for coming over"; nl2br($str); 

It will add HTML line breaks before all eols.

Php - How to remove line breaks (no characters!) from the string, PHP_EOL is defined differently on different systems. Sometimes it is a line feed, and other times it is a carriage return followed by a line feed. As a result, this will fail in some circumstances, potentially creating an attack vector (for example, when creating email headers). PHP_EOL should only be used to output information and not decipher

PHP - write to file at end of each line

Assume I already have a text file which looks like:

This is line 1. This is line 2. This is line 3. . . . This is line n. 

How can I append data from an array to the END of each line?

The following ONLY attaches to the line following the last line.

appendThese = ; foreach($appendThese as $a) < file_put_contents('sample.txt', $a, FILE_APPEND); //Want to append each array item to the end of each line >
 This is line 1.append_1 This is line 2.append_2 This is line 3.append_3 . . . This is line n.append_n 
$list = preg_split('/\r\n|\r|\n/', file_get_contents ('sample.txt'); $contents = ''; foreach($list as $key => $item) $contents .= "$item.$appendThese[$key]\r\n"; file_put_contents('sample.txt', $contents); 

PHP and CSV file - how to detect end of line?, I'd recommend using php's built in csv file reading function fgetcsv() and not create your own: so the last item in the line has not a comma in the end - what getting me into troubles because I don't get expected output. – user984621. Dec 20, 2012 at 17:26.

PHP: Retrieving lines from the end of a large text file

I've searched for an answer for quite a while, and haven't found anything that works correctly.

I have log files, some reaching 100MB in size, around 140,000 lines of text. With PHP , I am trying to get the last 500 lines of the file.

How would I get the 500 lines? With most functions, the file is read into memory, and that isn't a plausible case for this matter. I would preferably stay away from executing system commands.

If you are on a 'nix machine, you should be able to use shell escaping and the tool 'tail'. It's been a while, but something like this:

notice the use of tick marks, which executes the string in BASH or similar and returns the results.

I wrote this function which seems to work quite nicely to me. It returns an array of lines just like file. If you want it to return a string like file_get_contents, then just change the return statement to return implode('', array_reverse($lines)); :

function file_get_tail($filename, $num_lines = 10) < $file = fopen($filename, "r"); fseek($file, -1, SEEK_END); for ($line = 0, $lines = array(); $line < $num_lines && false !== ($char = fgetc($file));) < if($char === "\n")< if(isset($lines[$line]))< $lines[$line][] = $char; $lines[$line] = implode('', array_reverse($lines[$line])); $line++; >>else $lines[$line][] = $char; fseek($file, -2, SEEK_CUR); > fclose($file); if($line
file_get_tail('filename.txt', 500); 

If you want to do it in PHP:

= $buffer_size ? $buffer_size : $pos; fseek($fp, $pos - $read_size, SEEK_SET); // prepend the current block, and count the new lines $input = fread($fp, $read_size).$input; $line_count = substr_count(ltrim($input), "\n"); // if $pos is == 0 we are at start of file $pos -= $read_size; if (!$pos) break; > fclose($fp); // return the last 50 lines found return array_slice(explode("\n", rtrim($input)), -$n); > var_dump(tail('/var/log/syslog', 50)); 

This is largely untested, but should be enough for you to get a fully working solution.

The buffer size is 1024, but can be changed to be bigger or larger. (You could even dynamically set it based on $n * estimate of line length.) This should be better than seeking character by character, although it does mean we need to do substr_count() to look for new lines.

Php - fputcsv adds a line ending on the last element, fputcsv adds a new line after each line, that's how it works. From the docs: fputcsv () formats a line (passed as a fields array) as CSV and write it (terminated by a newline) A new line at the end of a file is not an error, or something you need to worry about. Don't try to remove it, just leave it.

Can't explode string on end of line PHP

I'm writing a PHP app to take data from an RSS feed and store it ready to serve in a different format for a mobile app.

Everything's working ok, apart from the important bit that takes the data from a string. There are clearly new lines in the data, but I can't explode it! Here's my attempt so far in trying to store each line into an array. I've exhausted my knowledge and Google's results!!

 // Prepare the data $possibleLineEnds = array("\r\n", "\n\r", "\r"); $preparedData = trim($row['description']); // Loop through and replace the data foreach ($possibleLineEnds as $lineEnd) < $preparedData = str_replace($lineEnd, "\n", $preparedData); >// Explode the data into new rows $locationData = explode("\n", $preparedData); print_r($locationData); 

Any ideas, anything at all would be welcomed on this!

I can't mark this as answered because I don't have a rating of 10.

I've got it working! I know its not as neat as it could be, I plain don't understand patterns for the preg functions!

Here's the code that worked:

 // Prepare the data $possibleLineEnds = array("\r\n", "\n\r", "\r", "
", "
", "<br/>"); $preparedData = trim(htmlspecialchars_decode($row['description'])); // Replace the possible line ends $preparedData = str_replace($possibleLineEnds, "\n", $preparedData); // Explode the data into new rows $locationData = explode("\n", $preparedData); print_r($locationData);

Thanks for everyone's input, we got there in the end!

I would just use preg_split() to match any combination of \n and \r characters, rather than messing with the string using str_replace() just so we can explode() it.

Your entire code is reduced to a single line:

$output = preg_split('/(\n|\r)+/', $input); 

The only difference between this and your original solution is that if the input contains blank lines, they won't appear in the exploded output. But I think that's probably a good thing in your case.

If You can't split by new line. Split by unique string;

// Prepare the data $possibleLineEnds = array("\r\n", "\n\r", "\r", "\n"); $preparedData = trim($row['description']); // Loop through and replace the data foreach ($possibleLineEnds as $lineEnd) < $preparedData = str_replace($lineEnd, ". ", $preparedData); >// Explode the data into new rows $locationData = explode(". ", $preparedData); print_r($locationData); 

I've got it working! I know its not as neat as it could be, I plain don't understand patterns for the preg functions!

Here's the code that worked:

// Prepare the data $possibleLineEnds = array("\r\n", "\n\r", "\r", "
", "
", "<br/>"); $preparedData = trim(htmlspecialchars_decode($row['description'])); // Replace the possible line ends $preparedData = str_replace($possibleLineEnds, "\n", $preparedData); // Explode the data into new rows $locationData = explode("\n", $preparedData); print_r($locationData);

Thanks for everyone's input, we got there in the end!

$preparedData = str_replace("\r", "", $preparedData); $locationData = explode("\n", $preparedData); 

and this worked for me all the time, I hope it helps you out

Explode PHP string by new line, Lots of things here: You need to use double quotes, not single quotes, otherwise the escaped characters won't be escaped. The normal sequence is \r\n, not \n\r.; Depending on the source, you may just be getting \n without the \r (or even in unusual cases, possibly just the \r); Given the last point, you may find preg_split() using all the possible variants will give you a …

Источник

Читайте также:  Java create class with parameters
Оцените статью