Echo index of array before \t - php

I have a txt file of trivia questions. I have split them into 2 array indexes and are seperated with a \t. I need to print those questions to the user in order and I don't know how to display part of the array index before the first \t.
<?php
session_start();
$file = "trivQuestions.txt";
$result = file($file);
$_SESSION['question'] = array();
$_SESSION['correctAnswers'] = array();
var_dump($_SESSION['question']);
foreach ( $result as $content ) {
$question = explode("\t", $content);
// echo $question[0];
//echos all questions
var_dump($question[0]);
//echo $question[0];
//echos all answers
//echo $question[1];
}
if (isset($_POST['submit'])){
}else{
echo "Welcome to trivia! Enter your answer below.";
}
?>

As your file has a question and answer separated by a tab on each new line in the file, you will have to split your file by each new line first. After that you will be able to loop trough each line of the file and split it by a tab.
From here you could add you split into a new array or do whatever you want to do with it.
In the code below I tried to demonstrate how such a split with loop would work, according to your description.
$file = "trivQuestions.txt";
$result = file($file);
// before you split by \t, you have to split by each new line.
// this will get you an array with each question + answer as one value
// PHP_EOL stands for end of line. PHP tries to get the end of line by using the systems default one. you can adjust that, if it a specific
// linebreak like "\n" or something else you know of.
$lines = explode(PHP_EOL, $result);
// var_dump($lines); <- with this you would see that you are on the right way
// setup a questions array to fill it up later
$questions = array();
// lets loop trough the lines
foreach ($lines as $line) {
// now you can explode on tab
$entry = explode("\t", $line);
// according to you description the question comes first, the answer later split by tab
// so we fill the questions array
$questions[] = $entry[0]; // the 0 element will be the question. if you want to adress the answer, use $entry[1]. maybe you want to add this in an other array for checks?
}
// this will give you the first question
var_dump($questions[0]);
If I have missed something or misunderstood parts of your question, let me know. Maybe I can adjust this code, to make it work as you need it to be.

Related

Remove Line from String within txt file

Currently I have a code, which displays data from a txt file, and randomizes it after converting it into an array.
$array = explode("\n", file_get_contents('test.txt'));
$rand_keys = array_rand($array, 2);
I am trying to make it so that, after this random value is displayed.
$search = $array[$rand_keys[0]];
We're able to store this into another txt file such as completed.txt and remove the randomized segment from our previous txt file. Here's the approach I tried, and surely didn't work out with.
$a = 'test.txt';
$b = file_get_contents('test.txt');
$c = str_replace($search, '', $b);
file_put_contents($a, $c);
Then to restore into a secondary file, I was messing with something like this.
$result = '';
foreach($lines as $line) {
if(stripos($line, $search) === false) {
$result .= $search;
}
}
file_put_contents('completed.txt', $result);
This actually appears to work to some extent, however when I look at the file completed.txt all of the contents are EXACTLY the same, and there's a bunch of blank spaces being left behind within test.txt
There are some better ways of doing it (IMHO), but at the moment you are just removing the actual line without the new line character. You may also find it will replace other lines as it just replaces the text without any idea of content.
But you will probably fix your code with the addition of replacing the new line...
$c = str_replace($search."\n", '', $b);
An alternative way of doing it is...
$fileName = 'test.txt';
$fileComplete = "completed.csv";
// Read file into an array
$lines = file($fileName, FILE_IGNORE_NEW_LINES);
// Pick a line
$randomLineKey = array_rand($lines);
// Get the text of that line
$randomLine = $lines[$randomLineKey];
// Remove the line
unset($lines[$randomLineKey]);
// write out new file
file_put_contents($fileName, implode(PHP_EOL, $lines));
// Add chosen line to completed file
file_put_contents($fileComplete, $randomLine.PHP_EOL, FILE_APPEND);

str_split adding empty elements in array end when reading from file

I found interesting problem while I was trying to achieve something simple like splitting string into array. The only difference here is that Im trying to take the string from .txt file
My code is the following:
$handle = fopen("input.txt", "r"); // open txt file
$iter = fgets($handle);
// here on first line I have the number of the strings which I will take. This will be the for loop limitation
for ($m = 0; $m < $iter; $m++)
{
$string = fgets($handle); // now getting the string
$splited = str_split($string); //turn it into array, this is where problem appears
print_r ($splited); // just show the array elements
echo "<br>";
echo count($splited);
echo "<br>";
}
This is the content of my .txt file
4
abc
abcba
abcd
cba
I tried with array_filter() and all other possible solutions/functions. Array filter and array diff are not removing the empty elements, no idea why... Also in my txt file there are no blank spaces or anything like that. Is this a bug in a str_split function ? Any logic behind this ?
The extra whitespace is a newline. Each row except the last technically contains all of the text contents you see, plus a newline.
You can easily get rid of it by e.g.
$string = rtrim(fgets($handle));
Also, fgets($fp); makes no sense since there's no variable $fp, should be fgets($handle); given your above code.
Trimming the spaces and need to change your fgets($fp) to fgets($handle) as there's no variable like of $fp.You need to update your code into as
for ($m=0;$m<$iter;$m++)
{
$string = trim(fgets($handle)); //
$splited = str_split($string); //turn it into array, this is where problem appears
print_r ($splited); // just show the array elements
echo "<br>";
echo count($splited);
echo "<br>";
}

PHP extract data from text file and write to another file

This is my first post on the internet for some assistance with coding so please bear with me!
I have been finding open code on the internet for a few years and modding it to do what I want but I seem to have come up against a wall with this one that I am sure is very simple. If you would please be able to help me it would be very much appreciated.
I have the following page:
<?php
$text = $_REQUEST['message'];
$f = file_get_contents("all.txt");
$f = explode(", ", $f);
function modFile($pos, $tothis, $inthis)
{
foreach($inthis as $pos => $a){
}
$newarr = implode("\r\n", $inthis);
$fh = fopen("example.txt", "w");
fwrite($fh, $newarr);
fclose($fh);
}
modFile(4, '', $f);
I have a file (all.txt) with the following:
11111111111, 22222222222, 33333333333, 44444444444
That I wish to display like this:
11111111111
22222222222
33333333333
44444444444
and to add a space then some text after each number where the text is the same on each line:
11111111111 text here
22222222222 text here
33333333333 text here
44444444444 text here
I have an html form that passes the custom text to be appended to each line.
I need to keep the file all.txt intact then save the newly formatted file with a different name.
I have tried putting variables into the implode where I currently have the "\r\n" but this does not work.
Any help very much appreciated.
Thanks in advance!
A few notes about your code: You are passing $pos to the function but it will get overwritten in the foreach. Also the foreach is empty, so what's it good for? And I don't see you use $text anywhere either.
To achieve your desired output, try this instead:
file_put_contents(
'/path/to/new.txt',
preg_replace(
'/[^\d+]+/',
' some text' . PHP_EOL,
file_get_contents('all.txt')
)
);
The pattern [^\d+]+ will match any string that is not a consecutive number and replace it with "some text " and a new line.
A somewhat more complicated version achieving the same would be:
file_put_contents(
'/path/to/new.txt',
implode(PHP_EOL, array_map(
function ($number) {
$message = filter_var(
$_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS
);
return sprintf('%s %s', trim($number), $message);
},
array_filter(str_getcsv(file_get_contents('/path/to/all.txt')))
)
));
This will (from the inside out):
Load the content of all.txt and parse it as CSV string into an array. Each array element corresponds to a number.
Each of these numbers is appended with the message content from the POST superglobal (you dont want to use REQUEST).
The resulting array is then concatenated back into a single string where the concatenating character is a newline.
The resulting string is written to the new file.
In case the above is too hard to follow, here is a version using temp vars and no lambda:
$allTxtContent = file_get_contents('/path/to/all.txt');
$numbers = array_filter(str_getcsv($allTxtContent));
$message = filter_var($_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS);
$numbersWithMessage = array();
foreach ($numbers as $number) {
$numbersWithMessage[] = sprintf('%s %s', trim($number), $message);
};
$newString = implode(PHP_EOL, $numbersWithMessage);
file_put_contents('/path/to/new.txt', $newString);
It does the same thing.
Your foreach() closing brace is on the wrong place. You've missed the exact part of running the execution of the new file creation. Here:
$text = $_REQUEST['message'];
$f = file_get_contents("all.txt");
$f = explode(", ", $f);
function modFile($pos, $tothis, $inthis, $text){
$fh = fopen("example.txt", "w");
foreach($inthis as $pos => $a){
$newarr = $a." ".$text."\r\n";
fwrite($fh, $newarr);
}
fclose($fh);
}
modFile(4, "", $f, $text);
This is for formatting your new file as you desire, however, you're not passing the new $text['message'] you want to append to your new file. You could either modify your mod_file() method or pass it within the foreach() loop while it runs.
EDIT* Just updated the whole code, should be now what you aimed for. If it does, please mark the answer as accepted.

PHP Parse File, replacing not required items going wrong

I'm trying to parse each IP line from the following file (loading from the web) and I'm going to store the values in database so i'm looking to put them in to an array.
The file its loading has the following source:
12174 in store for taking<hr>221.223.89.99:8909
<br>123.116.123.71:8909
<br>221.10.162.40:8909
<br>222.135.5.38:8909
<br>120.87.121.122:8909
<br>118.77.254.242:8909
<br>218.6.19.14:8909
<br>113.64.124.85:8909
<br>123.118.243.239:8909
<br>124.205.154.181:8909
<br>124.117.13.116:8909
<br>183.7.223.212:8909
<br>112.239.205.245:8909
<br>118.116.235.156:8909
<br>27.16.28.174:8909
<br>222.221.142.59:8909
<br>114.86.40.251:8909
<br>111.225.105.142:8909
<br>115.56.86.62:8909
<br>59.51.108.142:8909
<br>222.219.39.194:8909
<br>114.244.252.246:8909
<br>202.194.148.41:8909
<br>113.94.174.239:8909
<br><hr>total£º 24¡£
So I guess I'm looking to take everything between the <hr>'s and add each line line by line.
However doing the following doesn't seem to be working (in terms of stripping it the parts i dont' want)
<?php
$fileurl = "**MASKED**";
$lines = file($fileurl);
foreach ($lines as $line_num => $line) {
$line2 = strstr($line, 'taking', 'true');
$line3 = str_replace($line2, '', $line);
print_r($line3);
}
?>
If you want to add the values to an array, why not doing that directly inside the loop? I'd do something like this:
$output = array();
foreach ($lines as $line) {
if(preg_match("/<br>\d/", $line)) {
$output[] = substr($line, 4);
}
}
print_r($output);
Look into PHP function explode: http://www.php.net/manual/en/function.explode.php
It can take a string, and create an array out of it, by splitting at a specific character. In your case, this might be <br>
Also, trim function can get rid of the whitespace when needed.

editing values stored in each subarray of an array

I am using the following code which lets me navigate to a particular array line, and subarray line and change its value.
What i need to do however, is change the first column of all rows to BLANK or NULL, or clear them out.
How can i change the code below to accomplish this?
<?php
$row = $_GET['row'];
$nfv = $_GET['value'];
$col = $_GET['col'];
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
$j = 0;
if (isset($csvpre[$row]))
{
$target_row = $csvpre[$row];
$info = explode("%%", $target_row);
if (isset($info[$col]))
{
$info[$col] = $nfv;
}
$csvpre[$row] = implode("%%", $info);
}
$save = implode("###", $csvpre);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);
?>
Use foreach or array_map to perform the same action on all elements of an array.
In this case, something roughly along these lines?
foreach($rows as &$row) {
$row[0] = NULL;
}
I don't have a ready answer for you but I would recommend checking out CakePHP's Set class. It does things like this very well and (in some methods) supports XPath. Hopefully you can find the code you need there.
Depending on the size of that file, this could be much more efficient than looping through:
$data = file_get_contents("temp.php"); //data = blah%%blah%%blah%%blah%%###blah%%blah%%blah
$data = preg_replace( "/^(.+?)(?=%%)/", "\\1", $data ); //Replace first column to blank
$data = preg_replace( "/(###)(.+?)(?=%%))/", "\\1", $data ); //Replace all other columns to blank
After that, write it back to the file as you did above.
This would need to be adjusted to allow for escape characters if your columns allow %% to appear consecutively within them, but other than that, this should work.
If you expect this csv file to get REALLY large, you should start thinking of looping through the file line by line rather than reading it completely into memory using file_get_contents. I would point you to fgets_csv, but I don't believe it is possible to get each csv line by any delimiter other than newline (unless you are willing to replace your ### separator with \r\n). If you end up going this way, the answer totally changes :P
For more information on Regex (specifically positive lookaheads) see Regex Tutorial - Lookahead and Lookbehind Zero-Width Assertions (also a great site for regex in general)

Categories