Explode function in PHP - php

I have the following notepad file;
dbName:
tableName:
numberOfFields:
I am trying to write a php app which assigns the value of dbName to $dbName, tableName to $tableName and numberOfFields to $numFields.
My code is:
$handle = #fopen("config.txt", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
list($dbName, $tableName, $numFields) = explode(":", "$buffer");
}
fclose($handle);
}
however, ":" doesn't work as there are line breaks in between dbName and table Name. How do I explode $buffer, keeping the line breaks in the notepad file?
Thank you.

Have a look at the file function. It takes care of opening and reading the file, and returns an array of lines from the file. You could then iterate through the array and operate on each line individually.
http://us.php.net/manual/en/function.file.php

you can do this:
$data=file_get_contents("file");
$s = preg_split("/\n\n+/m", $data);
print_r($s);

You can use the chr($INT); function to look for the line break in your explode call.
Your can find more on the chr function here:
http://php.net/manual/en/function.chr.php
Add you can find the ascii chars for line break at:
http://www.asciitable.com/

fgets returns only one line. There is no way $buffer would ever have all three items at once, so that assignment to list() is wrong. For the first line, explode() will return an array with two items: "dbName" (text before the colon) and "" (text after the colon).

Does this work:
list ($dbName, $tableName, $numFields) = explode (':', implode ('', file ('config.txt')));

If you're sure of the line contents, and the file will not grow arbitrarily large:
1 <?php
2
3 $handle = #fopen("config.txt", "r");
4 if ($handle) {
5 $buffer = "";
6 while (!feof($handle)) {
7 $buffer = $buffer . trim(fgets($handle, 4096));
8 }
9 fclose($handle);
10
11 list($dbName, $tableName, $numFields) = explode(":", $buffer);
12 }
13
14 ?>
The while loop will go through all the lines and concatenate onto the same buffer after removing whitespace. This leaves just the content separated by ":". This is now amenable to explode.
As Nicolas wrote, feof gets one line at a time, so the list assignment needs to happen outside the loop.

Related

PHP add line in between two lines in textfile

I need to insert a line in a textfile between two other lines:
1: 30-12:32 1
2: 30-12:34 1
3: 30-12:35 1
For an example I need to insert a line between 1 and 2 which says 30-12:34 0.
I have the code to calculate what needs to be inserted by looking at the previous number but I need help inserting the text.
Thank you
Use this and then
function replaceInFile($what, $with, $file){
$buffer = "";
$fp = file($file);
foreach($fp as $line){
$buffer .= preg_replace("|".$what."[A-Za-z_.]*|", $what.$with, $line);
}
fclose($fp);
echo $buffer;
file_put_contents($file, $buffer);
}
and then enter what as the line just before it in text and with as what you want after it.

PHP: Reading word by word?

I am trying to read a file one word at a time. So far I have been able to use fgets() to read line by line or up to a certain amount of bytes, but that is not what I am looking for. I want one word at a time. up to the next white space, \n, or EOF.
Does anyone know how to do this in php. In c++ I just use the 'cin >> var' command.
you can do this by
$filecontents = file_get_contents('words.txt');
$words = preg_split('/[\s]+/', $filecontents, -1, PREG_SPLIT_NO_EMPTY);
print_r($words);
this will give you array of words
For some replies in this topic: I say this: Do not reinvent the wheel.
In PHP use:
str_word_count ( string $string [, int $format [, string $charlist ]] )
format:
0 = Return only the number of words;
1 = Return an array;
2 = Return an associative array;
charlist:
Charlist are characters which you consider a word.
Function.str-word-count.php
[CAUTION]
Nobody know anything about the size of your file content, if your file contents is big, exists many flexible solutions.
(^‿◕)
You would have to use fgetc to get a letter at a time until you hit a word bountry then do something with the word. Example
$fp = fopen("file.txt", "r");
$wordBoundries = array("\n"," ");
$wordBuffer = "";
while ($c = fgetc($fp)){
if (in_array($c, $wordBountries)){
// do something then clear the buffer
doSomethingWithBuffer($wordBuffer);
$wordBuffer = "";
} else {
// add the letter to the buffer
$wordBuffer.= $c;
}
}
fclose($fp);
You can try fget() function which read file line by line and when you get one line from file you use explode() to extract word from line which separated by space.
Try this code:
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
$word_arr = explode(" ", $line); //return word array
foreach($word_arr as $word){
echo $word; // required output
}
}
fclose($handle);
} else {
// error while opening file.
echo "error";
}

parsing a file from end

I have a text file that has information like this
##john##eva##shawn##roger##henry##david
I want to get the very last name at the end and ingnore rest.
How'd I do that
THanks
Big file solution:
$handle = fopen("myfile.txt", "r");
$file_size = filesize("myfile.txt");
$seek_position = -1024;
fseek($handle, $seek_position, SEEK_END);
while(strpos($data = fread($handle, abs($seek_position)), '##') === false){
$seek_position = $seek_position - 1024;
if(abs($seek_position) > $file_size)
break;
fseek($handle, $seek_position, SEEK_END);
}
$val = substr(2, $data);
Small file solution:
$file_contents = get_file_contents($file_location);
$array = explode('##', $file_contents);
$val = $array[end(array_keys($array))];
unset($array);
Use fseek to quickly jump to the end of the file.
$handle = fopen("myfile.txt", "r");
fseek($handle, -20, SEEK_END);
$bytes = fread($handle, 20);
Will read the last 20 bytes of the file (and skip the rest).
Unless you know how long the last name is going to be or at least the max length of names you can't really skip just to end of a file and pull out the name.
What you need to do is read the file into a buffer and parse it either using something like explode() and '##' and getting the last element of the returned array or using strpos() to find the last occureance of '##'and reading on from there.
Here is an example with explode.
$sFileName = "file.txt";
$sContents = file_get_contents($sFileName);
$aNames = explode("##", $sContents);
$sLastName = $aNames[count($aNames)-1];
After loading the file into a variable, you can find the last ocurrence of "##" using strpos() and then read from there on using substr().
You can explode the whole string to an array and then use the php's end() function, like this:
// define our string
$string = "##john##eva##shawn##roger##henry##david";
// use the explode function to create an array using the delimiter ##
$array = explode("##", "##john##eva##shawn##roger##henry##david");
// print last object of the array using the php's end function
print end($array);

How to read line by line in php

when i try to insert each line into my oracle database i get an error stating invalid number, but if have only one line in the file it works fine.
$file = #fopen('file.text', "r") ;
// while there is another line to read in the file
while (!feof($file))
{
// Get the current line that the file is reading
$currentLine = fgets($file) ;
$currentLine = explode(' ',$currentLine) ;
insert($currentLine) ;
}
fclose($file) ;
the lines look like this
1 4 100
1 4 101
Try this:
$currentLine = trim(fgets($file));
It's possibly failing on the newline/carriage-return at the end of the line.
If not, where is this insert() function defined? Build a debug section that echos or writes out the attempted queries so you can really see the issue.
Your explode() call is using 9 spaces as a separator, but your file only appears to have 5 spaces between each number. This means your $currentline be a single element array containing the original line, and not separate elements with a number in each.
Either change the number of spaces in the explode call, or change to
$currentLine = preg_split('/\s+/', $currentLine);
which will split on any number of sequential spaces.
I would double check that there is not a new line at the end of the file. Maybe even double check inside of php that the line read is not blank.
$lineCount=0;
// while there is another line to read in the file
while (!feof($file))
{
$lineCount++;
// Get the current line that the file is reading
$currentLine = fgets($file);
if(trim($currentLine) != ''){
$currentLine = explode(' ',$currentLine) ;
insert($currentLine) ;
echo "Inserted line number $lineCount<br />";
} else {
echo "There was a blank line at line number $lineCount.<br />";
}
}
$lines = explode("\n", str_replace("\r", "", file_get_contents("file.text")));
foreach ($lines as $line)
{
insert(explode(' ', $line);
}
try this :
// Read all data in the file
$file_all = file_get_contents('file.text') or die("unable to open file");
// create an array with each index = a line
$file_lines = explode(chr(13),$file_all);
// Insert each line found
foreach ($file_lines as $file_line) { insert($file_line); };

How do I read a text file into array of lines and display it using PHP?

I have text file that looks like this:
1 1 1 1
1 2 3 5
4 4 5 5
I want to read this text file into array of lines and display it. Can anyone help me do this?
This should get you going: php function file
<?php
$cont = file_get_contents("data.txt");
$lines = explode("\n",$cont); // $lines is now an array containing each line
// do something with data here
?>
make sure you use the correct line endings however as Windows uses \r\n and UNIX uses \n.
you can use fopen(), fgets(). see here
eg
$f=fopen("file","r");
if($f){
while (!feof($f)) {
$line = fgets($f, 4096);
print $line;
}
fclose($f);
}
You'd want to do something like this:
<?
$filename = "somefile.txt";
$arr = file($filename);
foreach($arr as $line){
print $line . "<br />";
}
?>
This one is working for me.
$array = explode("\n", file_get_contents('file.txt'));

Categories