Jump to content

Help parsing txt file using php


cyberland

Recommended Posts

Hi all,

 

I have a text file with few IP ranges in the following format:

 

1.52.0.0 - 1.55.255.255

 

What I hope I can do is to loop through the file content and retrieve the start IP / end IP (each in a variable) so that I can work on each of them. So for example for the line above I wish to get (1.52.0.0) in a var and (1.55.255.255) in another var while looping the file content

 

So I was wondering if I can get any help on how to do this using PHP?

 

Please excuse me if this seem to be very easy question but I am quite new to php, so any code help will be highly appreciate

 

Thanks for your time

 

Mark

Link to comment
https://forums.phpfreaks.com/topic/238157-help-parsing-txt-file-using-php/
Share on other sites

Suggestion: file to get each line in the file, foreach to loop over the array you get back from it, and explode to split each line into the two address halves.

 

Thanks a lot for your help and time, any chance you can offer me any sample code / example as I am literary new to the php and programming world?

 

Thanks for your time

well file() returns an array with all the lines of the file. So if we do this

$lines = file("path/to/file.txt");

$lines would contain all the lines from the text file. Because its an array, we can use the foreach loop to go through each of the lines easily. For example

foreach($lines as $line){
//do something with them
}

 

explode will basically split up a string into an array of the pieces, based on some delimiter. so for example

$str = "190.0.0.0 - 190.255.255.255";
//the delimiter is " - " since we just want the two ips
$pieces = explode(" - ", $str);
$firstPart = $pieces[0];//the low end of the range is the first index of the array
$secondPart = $pieces[1];//the high end of the range is the second index of the array

 

So, to put it all together

 

$lines = file("path/to/file.txt");
//get the lines from the text file

foreach($lines as $line){//loop through each of the lines
//explode the line to get the two pieces of the string
$pieces = explode(" - ", $line);
//store the first part
$firstPart = $pieces[0];
//store the second part
$secondPart = $pieces[1];
}

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.