php explode line by line
How to read a large file line by line?
I want to read a file line by line, but without completely loading it in memory.
My file is too large to open in memory, and if try to do so I always get out of memory errors.
The file size is 1 GB.
14 Answers 14
You can use the fgets() function to read the file line by line:
If you’re opening a big file, you probably want to use Generators alongside fgets() to avoid loading the whole file into memory:
This way you can process individual file lines inside the foreach().
Note: Generators require >= PHP 5.5
There is a file() function that returns an array of the lines contained in the file.
Use buffering techniques to read the file.
The obvious answer wasn’t there in all the responses.
PHP has a neat streaming delimiter parser available made for exactly that purpose.
This how I manage with very big file (tested with up to 100G). And it’s faster than fgets()
SplFileObject is useful when it comes to dealing with large files.
Explode in one line
I want to explode text word by word, but in one line. Not line by line. I’ve got this:
With this it look like this :
But i want it this way:
And every word have a link.
6 Answers 6
means a line break. So, if you don’t want a new line between each word, don’t put a
between each word.
The reason it separates onto new lines is because you put them it. Just remove the
s:
EDIT
You can actually do this in one line with a Regex:
Use array_map for this (and implode to glue everything back into a string):
You can do it in one line if you don’t mind the readability.
You’re including line breaks manually. Simply remove
:
Not the answer you’re looking for? Browse other questions tagged php explode or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How can I put strings in an array, split by new line?
I have a string with line breaks in my database. I want to convert that string into an array, and for every new line, jump one index place in the array.
The result I want is this:
19 Answers 19
I’ve always used this with great success:
(updated with the final \r, thanks @LobsterMan)
You can use the explode function, using » \n » as separator:
For instance, if you have this piece of code:
You’d get this output:
Note that you have to use a double-quoted string, so \n is actually interpreted as a line-break.
(See that manual page for more details.)
A line break is defined differently on different platforms, \r\n, \r or \n.
Using RegExp to split the string you can match all three with \R
So for your problem:
That would match line breaks on Windows, Mac and Linux!
PHP already knows the current system’s newline character(s). Just use the EOL constant.
What’s happening is:
Since line breaks can come in different forms, I str_replace \r\n, \n\r, and \r with \n instead (and original \n are preserved).
Then explode on \n and you have all the lines in an array.
I did a benchmark on the src of this page and split the lines 1000 times in a for loop and:
preg_replace took an avg of 11 seconds
str_replace & explode took an avg of about 1 second
More detail and bencmark info on my forum
David: Great direction, but you missed \r. this worked for me:
PHP_EOL is a constant holding the line break character(s) used by the server platform.
The » (instead of ‘) is quite important as otherwise, the line break wouln’t get interpreted.
StackOverflow will not allow me to comment on hesselbom’s answer (not enough reputation), so I’m adding my own.
This worked best for me because it also eliminates leading (second \s*) and trailing (first \s*) whitespace automatically and also skips blank lines (the PREG_SPLIT_NO_EMPTY flag).
If you want to keep leading whitespace, simply get rid of the second \s* and make it an rtrim() instead.
If you need to keep empty lines, get rid of the NULL (it is only a placeholder) and PREG_SPLIT_NO_EMPTY flag, like so.
Or keeping both leading whitespace and empty lines.
I don’t see any reason why you’d ever want to keep trailing whitespace, so I suggest leaving the first \s* in there. But, if all you want is to split by new line (as the title suggests), it is THIS simple (as mentioned by Jan Goyvaerts).
As other answers have specified, be sure to use explode rather than split because as of PHP 5.3.0 split is deprecated. i.e. the following is NOT the way you want to do it:
LF = «\n» = chr(10), CR = «\r» = chr(13)
There is quite a mix of direct and indirect answers on this page and some good advice in comments, but there isn’t an answer that represents what I would write in my own project.
The OP makes no mention of trimming horizontal whitespace characters from the lines, so there is no expectation of removing \s or \h while exploding on variable (system agnostic) new lines.
While PHP_EOL is sensible advice, it lacks the flexibility appropriately explode the string when the newline sequence is coming from another operating system.
Using a non-regex explode will tend to be less direct because it will require string preparations. Furthermore, there may be mopping up after the the explosions if there are unwanted blank lines to remove.
Splitting a line of text in PHP
PHP allows you to split a line of text into its component parts. For example, if you were reading from a text file line by line you might have to break apart a line like this:
Poll number 1, 1500, 250, 150, 100, 1000
If this were a poll, and you want to display the results for all to see, then you might be trying to print something like this on the page:
Poll Number 1
Respondents: 1500
Answer A: 250
Answer B: 150
Answer C: 100
Answer D: 1000
The line of text is separated by commas. As the line is read in (which we’ll see how to do in a later section), you’d be passing it to a variable. You’d then need to chop the text up, based on the comma. We can simulate that. First, pass the text to a variable:
$text_line = «Poll number 1, 1500, 250, 150, 100, 1000»;
The next job is to split this text apart, so that PHP knows about all the separate pieces. The pieces we want are:
To split lines of text, the gloriously sounding explode( ) function can be used. You just provided it with the text you want to split, and the character that is used to separate each piece. Here’s the syntax:
explode( separator, string_to_split )
In between the round brackets of explode( ) the separator you want to use goes first, followed by a comma, then the string you want to split. For our line of code above, you’d do this:
So we’re saying, «Look for a comma in the text, and split the line of text into separate pieces.» Once PHP does its job, it puts all the parts into the variable on the left hand side of the equals sign ( = ), which was $text_line for us. This variable will then be an array!
To get at the pieces of the array, access it in the normal manner. Here’s some code to try:
Run the code and see what happens. Then change the 0 of the print statement to 1, then to 2, then to 3, then to 4, then to 5, and finally to 5. What happens when you enter 6 as the array Key number?
To see all the parts of your array, you can use a different form of print statement. Try changing the print line in your code from this:
Run your code and see what happens.
You should see your array details printed out, with all the Keys and the Values. The print_r( ) statement is quite useful, when you’re trying to debug your code.
And it does show that explode( ) works all of the values are in an array!
Another way to access all the element returned by explode( ) is with a for loop:
$text_line = «Poll number 1, 1500, 250, 150, 100, 1000»;
$text_line = explode(«,»,$text_line);
Php Explode By Line Break
Php Explode String By Newline | Online Tutorials
php explode break line. php explode by newline. php explode by line—break. explode on the base on new line in php. explode \n in php. get end of explode in one line php. php explode with new line. how to always show the end of an explode in php. get value from 0 to explode php.
21/10/2010 · Single quotes in PHP mean «don’t parse this string». That means your control characters aren’t being parsed, they’re being taken as literal (not a line break and a carriage return, but actual, literal ‘\n\r’). Using double quotes means «parse this string», and thus your control characters will be parsed. +1 –