0

I have a file we will call info.txt under UNIX format that has only the following in it:

#Dogs
#Cats
#Birds
#Rabbits

and am running this against it:

$filename = "info.txt";
$fd = fopen ($filename, "r");
$contents = fread ($fd,filesize ($filename));

fclose ($fd);
$delimiter = "#";
$insideContent = explode($delimiter, $contents);

Now everything looks to be working fine except when I display the array I get the following.

[0] => 
[1] => Dogs
[2] => Cats
[3] => Birds
[4] => Rabbits

I checked the .txt file to make sure there wasn't any space or hidden characters in front of the first # so I'm at a loss of why this is happening other than I feel like I'm missing something terribly simple. Any ideas?

Thanks in advance!

1
  • You can use $contents = file_get_contents("info.txt"); Commented Mar 17, 2010 at 0:18

5 Answers 5

6

explode() splits on the delimiter. If there is nothing before the first delimiter, then that's what the first element will be. Nothing. An empty string.

Sign up to request clarification or add additional context in comments.

2 Comments

Right. And to overcome this, I would suggest $contents = trim($contents, $delimiter). :)
Wow I didn't even think about it that way. I got in the sense of after the delimiter. That explains it all. Thank you!
2

I would guess that it's because the very first character is a delimiter, so it's putting whatever's to the left of it in the first element, even if it's an empty string. So you would have to start the file with "Dogs", not "#Dogs"

Comments

0

You're running it like

#Dogs#Cats#Birds#Rabbits

PHP splits it by cutting, thus where you have Dogs it sees it like 'Blank Space' | Dogs.

You can easily fill [0] by using array_shift($input, 1);

Comments

0

You could explode by newlines and not use the # at all although then you would have a trailing empty item. I guess you still have to do some integrity check (remove the first/last item if empty) after parsing.

Comments

0

another way

$f=file("file");
print_r( preg_replace("/^#/","",$f) ) ;

1 Comment

Well, your code would cause another issue: the trailing new line will be included in each array item. Use the flag FILE_IGNORE_NEW_LINES. Apart from that, It's pretty clever and elegant. Wondering which solution would perform best.

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.