parsing a file from end - php

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);

Related

PHP parse_url doesn't work with array element

<?php
$urls = file('urls.txt');
foreach ($urls as $url) {
print(parse_url($url));
}
?>
parse_url takes string as argument but not array element with type string. What should I do?
There's no difference between a string and an array element of type string.
Your problem is most likely that file() by default includes in each array element the newline at the end of each line in the file. See:
http://php.net/manual/en/function.file.php
You're going to need to use FILE_IGNORE_NEW_LINES to make it not do this (see link for details)
You could take a different approach when reading the file. Take this example:
$fp = fopen('urls.txt', 'r');
while(($buffer = fgets($fp, 1024)) != NULL){
//where 1024 is maximum length of each line in file
if(gettype($buffer) == 'string'){
echo "$buffer\n";
}
}
fclose($fp);
Hope this helps you.

PHP insert in file

I have to insert text to a file at a specific position without reading/writing the entire file. Is that possible using just php?
mytext.txt content is 123456789
<?php
$message='new';
$file='mytext.txt';
$fh = fopen($file, 'rw+');
fseek($fh, 3);
fwrite($fh, $message);
fclose($fh);
?>
This code overwrites at the specified location.
I'm looking for '0123new456789' not '123new789'
I don't think what you want to do is possible without reading the file first. This should help, though:
// Get file contents
$contents = file_get_contents($file);
// Split your strings
$beginning = substr($contents, 0, 4);
$ending = substr($contents, 4, 6);
// Re-write contents
$contents = $beginning . $message . $end;
// Write file contents
file_put_contents($file, $contents);
Thanks,
Andrew
You have no choice.
fopen() allways put the pointer at the beginning or end of file. In any case you must to pass trough the file untill you find what you are looking for. There you can close.
See the document about it http://php.net/manual/en/function.fopen.php
By the way, fseek($fh, 3) is not mean to find 3. Is is retrieve something in the 3 bytes length. See http://php.net/manual/en/function.fseek.php

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";
}

textfile to an array...any ideas?

I am needing to turn a textfile into an array...I am not sure how to go about this because the other features ive seen for php take an entire file and put it into an array but not quite how I want it to be so I am looking for advice here..
The following is written in a textfile:
"jim kroi,richard wuu,yan kebler,justin persaud"
How can I use php to make an array where automatically a loop puts each name as an item of the array until all the names run out?
so the end result of what I am trying to do is:
$array= array("jim kroi","richard wuu","Yan kebler","justin persaud");
So a loop of some sort would basically search upto each comma and extract the name before it until all of the names run out....
There are some php substr and such functions but I cant quite think of how to do this..
Yes, I do have code, here it is:
<?php
error_reporting(-1);
$fp = fopen('numbers.csv', 'w');
fputcsv($fp, $_POST['names']);
fputcsv($fp, $_POST['numbers']);
fclose($fp);
?>
i put them all in a csv but now how can I make 2 arrays, one with name the other with numbers? http://imageshack.us/photo/my-images/215/csv.png/
using implode I get the error:
Warning: implode() [function.implode]: Bad arguments. in C:\Program Files\xampp\htdocs\xampp\something.php on line 14
<?php
error_reporting(-1);
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r'); // open file
$theData = fread($fh, 5); // read file and store in var
$array = explode("\n", $theData); // explode string by lines using \n
echo implode("<br/>", $theData); // put the array back together and show each item as a line
fclose($fh);
?>
Try to use fgetcsv with a custom separator.
Something like:
$names = array_map('trim', explode(',', file_get_contents('%yourFileHere')));
Use the explode() function.
$string = "jim kroi,richard wuu,yan kebler,justin persaud";
$arrNames = explode(',', $string);
var_dump($arrNames);
see explode, read the file with file_get_contents
You can try explode;
$names = explode(',', $line);
http://php.net/manual/en/function.explode.php
it's simple
<?PHP
$myFile = "testFile.txt"; // file path and name
$fh = fopen($myFile, 'r'); // open file
$theData = fread($fh, 5); // read file and store in var
$array = explode("\n", $theData); // explode string by lines using \n
echo implode("<br/>", $theData); // put the array back together and show each item as a line
?>

Explode function in 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.

Categories