newline character question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

newline character question

Post by liljester »

i have a tab-delimited textfile that i want to import into a database. my problem is that there are some newline (\n or hex 0x0a) characters scattered throughout the file. I need to strip these newlines out, whilst keeping the other newline (\r\n or hex 0x0d + hex 0x0a) characters that mark the true line endings..

anyideas?
slimsam1
Forum Commoner
Posts: 49
Joined: Wed Aug 21, 2002 12:20 am

Re: newline character question

Post by slimsam1 »

liljester wrote:i have a tab-delimited textfile that i want to import into a database. my problem is that there are some newline (\n or hex 0x0a) characters scattered throughout the file. I need to strip these newlines out, whilst keeping the other newline (\r\n or hex 0x0d + hex 0x0a) characters that mark the true line endings..

anyideas?
Well, a sorta hackjob way would be to go through the file with str_replace and replace all the \r\n with some weird combination of characters, like ***___***, remove all of the remaining \n's, then replace all the ***___*** with \r\n again...
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Post by liljester »

ive tried to replace the carriage return (\r, hex 0x0d, ascii 13) but for some reason PHP refuses to do anything with the carriage return... i know that its in the file, because i opened it with a hex editor, and the chars i want out are "0x0a" and the line endings are "0x0d" followed by "0x0a".

if i try to do a str_replace(chr(13), "*********", $string) it does nothing.
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

WHOOOHOOOOO!

Post by liljester »

Its fixed! *does a jig*

here's what the problem was....
$whole_file = fread("file.txt", "r");

should have been
$whole_file = fread("file.txt", "rb");
or
$whole_file = file_get_contents("file.txt");

hehe im not exaclty sure why the "b" (binary?) fixed the problem of php not being able to see the chr(13) character... but it did =)
Post Reply