0

I have a text file with these contents

00:00:00:23 You
00:00:01:04 would
00:00:01:10 not
00:00:01:20 believe
00:00:02:07 your
00:00:02:16 eyes
00:00:03:08 -
00:00:03:16 if
00:00:03:20 ten
00:00:04:01 million
00:00:04:13 fireflies
00:00:06:00 -
00:00:06:08 lit
00:00:06:17 up
00:00:07:01 the
00:00:07:04 world
00:00:07:13 as

Notice how between each timestamp there is a new line. If I do file_get_contents and print it it will display in the browser exactly as shown with new line as wanted. However, I want to get each new line as a separate array element. When I use file(), only one element with the whole txt file is returned, and even if I write

ini_set("auto_detect_line_endings", true);

at the start of the script, most of the lines are put in arrays but some are not. If I try to explode with the "\n" delimiter, well that doesn't work at all.

6
  • Is it a windows file? Try to explode it on \r\n Commented Aug 7, 2017 at 15:24
  • nah mac. tried that it didn't work Commented Aug 7, 2017 at 15:27
  • you know what, I just copied and pasted the text into some online html converter and pasted it back and it worked fine. Doesn't explain why this is happening tho. Commented Aug 7, 2017 at 15:34
  • You might have hidden characters in your text that break things. try something like this $text=iconv("UTF-8", "ISO-8859-1//IGNORE", $text); then break on new line Commented Aug 7, 2017 at 15:54
  • Open a terminal and use od -c your_file_name.txt to see if there are any weird line-break variations in your file - either \n for unix, \r for "classic" mac or \r\n for windows. Commented Aug 10, 2017 at 0:27

1 Answer 1

2

This should work:

$lines = explode("\n", file_get_contents('foo.txt'));

also try to explode on: "\025" or "\r"

latest example, please try this one:

also try:

<?php
$lines =file_get_contents('foo.txt');
$lines = preg_split("/\\r\\n|\\r|\\n/", $lines);
print_r($lines);
?>
Sign up to request clarification or add additional context in comments.

3 Comments

nope, told you i already tried explode, but not with \025, but that still didn't work
I have an updated example above, this expression has a chance to properly detect new lines: "/\\r\\n|\\r|\\n/" can you try again? Can you update your file to some location so we can use it?
Please use the solution which includes preg_split("/\\r\\n|\\r|\\n/", $lines); Here is what I have done to test if this works:I have saved file with Mac line ending options in PSPad Editor then I have tried all three options (\n,\025,\r) none of them worked, however /\\r\\n|\\r|\\n/ gives the desired output: Array ( [0] => 00:00:00:23 You [1] => 00:00:01:04 would [2] => 00:00:01:10 not...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.