Jump to content

replace space with new line


ballhogjoni

Recommended Posts

I have a txt file that has a lot of ip addresses and they are aligned like this:

58.2.0.0 58.2.255.255

58.68.0.0 58.68.127.255

58.146.96.0 58.146.127.255

59.88.0.0 59.99.255.255

 

I want to replace the space with a new line. I tried this code:

$lines = file_get_contents('asdfsdf.txt');

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, str_replace(' ','\n',$lines));
fclose($fh);

 

which replaces the space with the \n but it doesn't add a new line to the txt file.

 

any ideas. My end goal is to enter this txt file into my db.

Link to comment
https://forums.phpfreaks.com/topic/127773-replace-space-with-new-line/
Share on other sites

ok that worked great thanks. Now I tried to insert each line of the file into my db creating a new row for each line. It didn't work and I don't know where I went wrong. Any ideas?

 

<?php
$lines = file_get_contents('testFile.txt');
$sa = array($lines);
foreach($sa as $num => $line){
mysql_query('INSERT INTO ip_tracking (ip) values ("' . mysql_real_escape_string($line) . '")');
}
?>

That will not get you an array of lines, you want to use the file() function instead:

<?php
$lines = file('testFile.txt');
foreach ($lines as $line) {
   $q = "INSERT INTO ip_tracking (ip) values ('" . mysql_real_escape_string(trim($line)) . "')";
   $rs = mysql_query($q) or die("Problem with the query: $q<br>" . mysql_error());
}
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.