Ask how to split the txt file by blank lines,

Source: Internet
Author: User
Ask how to split the txt file by blank lines, and ask how to split the txt file by blank lines,
For example, txt file a.txt

The content is as follows:
Ah, ah
Er, er

111111
222222

Ga
Ga

If there is a blank line in it, how can we cut it into a character string in the segment?


Reply to discussion (solution)

$ Content = file_get_contents ('./a.txt ');
$ Rows = explode ("\ r \ n", $ content );

Call the function file.

If it is split by blank lines, we need to find two line breaks (\ r \ n ).
$ Str = '2017
Defsf

Abc
1213

&*(
';
Print_r (explode ("\ n \ r", $ str); // equivalent to print_r (explode ("\ r \ n", $ str ));
Or use regular expressions.
Preg_match ('/[^.] +? (? = \ R \ n)/', $ str, $ mat );
Print_r ($ mat );

Use preg_match_all for the regular expression.

$ S = <TXT ah er) \ 1/", $ s); print_r ($ );
Array ([0] => Ah ah er [1] => 111111222222 [2] => Ga)

$ S = <TXT ah er) \ 1/", $ s); print_r ($ );
Array ([0] => Ah ah er [1] => 111111222222 [2] => Ga)


The result of my testing of this code is:
Array ([0] => Ah, ah, er, er, 111111, 222222)

If the file data is small, you can read the content at one time and use the explode method to split it.
If the file size is very large, one-time loading will inevitably lead to excessive memory usage and low performance. In this case, you can read the open file row by row and verify the row data for segmentation.

$ Content = file_get_contents ('./a.txt ');
$ Rows = explode ("\ r \ n", $ content );



In this way, the line feed is used instead of space.
Array ([0] => Ah ah [1] => er [2] => [3] => 111111 [4] => 222222 [5] => [6] => Ga [7] => Ga [8] =>)

According to friends on the third floor, use $ rows = explode ("\ r \ n", $ content );
The output result is
Array ([0] => Ah, ah, er, er, 111111, 222222)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.