PDA

View Full Version : Line break mess?


gorilla1
03-11-2005, 03:19 AM
I'm having trouble with handling "/n" in a file, as follows...

I have a file I have created by this code, which contains the file names of some images:
$entry_line = ($value ) . "\n";
fwrite( $fp, $entry_line);

I then create an array by reading this file:
$data = file($filename);

And I want to write a new file the contains both the file names and extensions, 1.jpg, 2.jpg, etc., separated by "|".
So, I want to use:
$lineout = "|" . $lineout . ".jpg";
fputs($fp,$lineout);

However, the line break ("/n") gets in the way, and the files ends up like this:
|1
.jpg|2
.jpg|3
.jpg

If I try:
str_replace("/n", ".jpg\n", $lineout);
the "/n" is never seen, so the replace never occurs.
How can I output the records so they look like:
|1.jpg
|2.jpg

etc? (of course, the values, 1, 2, 3 etc. will vary, so I cannot just str_replace on them)

G

4xz
03-11-2005, 06:32 AM
$lineout = preg_replace("/\n/", ".jpg", $lineout);

This should be working as it ain't a /n you want to replace, but a \n. I would reccomend to use preg_replace as you can see :)

Also the result of the a replacement needs to be assigned to a variable.
Calling it like this :
preg_replace("/\n/", ".jpg", $lineout);
Will not alter the $lineout variable.

A nice trick to see what you're working with and to spot errors is to echo the values like this :
echo "*".$lineout."*";
This way you can immediately spot whitespace and newlines in your variable.

marek_mar
03-11-2005, 03:56 PM
The only difference here is that regex is slower. You don't need to use it since str_replace can do the same...

4xz
03-11-2005, 07:23 PM
Well, preg is far more powerfull and the performancepenalty in almost all cases is non significant. So in this light I would always reccomend to get used to using preg's :)

gorilla1
03-12-2005, 01:46 AM
Thanks!!

marek_mar
03-12-2005, 01:16 PM
Well, preg is far more powerfull and the performancepenalty in almost all cases is non significant. So in this light I would always reccomend to get used to using preg's :)In some places it does matter. If you have to replace \n with \r\n (example) in all strings in an array you will see it's slower.

4xz
03-12-2005, 04:30 PM
Which will not be noticable by an end user unless he's batching 500 MB + files. I will go for (de facto) standards, while you monitor every millisecond performance deterioration using a stopwatch :) Preg all the way ! ;-)