PHP Shuffle Text File and Rewrite Using File_Put_Contents - php

I've been trying for two days to create an array from a text file list, shuffle it, then rewrite the text file using file_put_contents.
I've succeeded in doing so BUT when I run the script more than once it creates multiple and random spaces between each item.
I've tried many different ideas but no joy yet.
Below is my code.
<?php
// create array from text file
$array = file('list.txt');
// shuffle the array
shuffle ($array);
// overwrite original with new shuffled text file
file_put_contents('list.txt', implode(PHP_EOL, $array));
?>

It seem like you may have extra line returns. These would also be part of the array and subject to random shuffling. IF you want to remove them you can do this
$array = array_filter(array_map('trim', $array));
The array map trim just runs trim() on every item in the array, this will help get rid of lines that have spaces in them instead of being strictly empty. Trim simply removes any whitespace from the front and back of a string, in the case that the whole line is whitespace then all the whitespace is removed leaving an empty string '' for that line.
The array filter will remove any lines that evaluate out to 0 in php this is '' 0 false null and maybe a few other things.
So by combining them we can easily filter out any lines that contain only whitespace or are empty.

Related

Are in_array() and file() compatible in php?

In the same location of my php file there's a "namestable.txt" file, full of names:
John
Alex
Tim
I have the following variable
$names = file("/names table.txt");
I tried to use the in_array with $names, but it doesn't work:
in_array($names)
I tested $names and I can echo all the values, so it behaves as a regular array.
I also created an array inside my php file and tested the in_array(), and it works with the PHP array. So, are file() and in_array() incompatible or I'm doing something wrong?
Your problem most likely is, that each line in namestable.txt ends with a newline (or carriage return and newline) character. So the array returned from file contains "John\n", "Alex\n" and "Tim\n".
If you pass the FILE_IGNORE_NEW_LINES to file, it will strip the newlines for you.
$names = file('namestable.txt', FILE_IGNORE_NEW_LINES);

HTML textarea alignment

Suppose I have textarea filled with following text
employee/company/salary
john/microsoft/12.000
michael/citrusdata/15.000
How can I align each column vertically so I get following text:
employee__________company__________salary
john______________microsoft__________12.000
michael___________citrusdata__________15.000
In this example I used underscores to specify whitespaces, thought to write a simple function like nl2br() to replace '/' with one or many tab characters but it wont be a consistent solution, guess I need to read text line by line and considering the length of every word, I need to replace '/' with enough whitespace but dont have any idea how to code it, is there any other way?
I suppose you will output the textarea content outside the textarea itself, else you will need to use js alternative. My answer uses php :)
So, you may use the sprintf function that allows left or right padding.
Just split your content to get an array of lines
$lines = explode("\n", $content);
Take care of a eventual empty last entry (if your content end with a \n)
Then
foreach($lines as $line) {
$items = explode("/", $line) ;
echo sprintf("%-15s%-15s%-15s", $items[0], $items[1], $items[2]) . "<br/>";
}
"%-15" tells to left-pad with 15 empty spaces.
It works on console, but you have to nl2br it before echoing in web pages !
This is sample, so you have to add error testing (lines with only one / for example).
You should specify the width of each column like 50 characters for each or any desired width. let say it $COLUMN_WIDTH = 100;
find length of the column value (string) than subtract it from fixed length like
$COUNT_SPACES_TO_INSERT = $COLUMN_WIDTH - strlen($COLUMN_STR);
Than insert $COUNT_SPACES_TO_INSERT number of spaces it will solve your issue.

Remove lines with specific pattern at the beginning of them

I have a text file of approximately 25,000 lines. About 525kb.
Some lines have random text at the beginning.
Some have long strings of semicolons.
Some others only have three semi-colons and then a space and optionally more text on the same line. These are the lines I want to remove.
Here is a sample....
;;; Updated Time 20120706122706
;;; Generic DEveloper Output
;;; Some Random Comments
;;; I got some more...
;;; Yet another uneeded line
;;; Thanks for using StackOverflow <http://stackoverflow.com>, or...
;;; Not.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Banana Production
[Data_Release_Version]
Version=12586
Released=20120706122706
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Baseline Properties
[BaseLineProperties]
Comment=BaselineProperties
----- and so on.
Once it gets to the first line with 4 or more ; on the line, I need the rest of the file as there are no ";;; " lines.
Trying to find something fast instead of reading everything line and writing it back out if it doesn't match ";;; ".
File is ASCII (possibly UTF-8) text type file.
Any ideas?
Thank you for your time, assistance and knowledge.
What I would suggest is to use file_get_contents() and save file's contents in a variable as a string, then use explode() that string at every newline character, then in a foreach loop, use preg_match() to check if the line begins with 3 semicolons and a space, if it dosent, put it in another array named $output. After foreach, implode() $output and add a newline character and use file_put_contents() to print it in another file. Hope this helps :-)
code:
<?php
$string = file_get_contents($filename);
$array = explode("\n",$string);
foreach($array as $arr) {
if(!(preg_match("^;;;\s",$arr))) {
$output[] = $arr;
}
}
$out = implode("\n",$output);
file_put_contents($path,$out);
?>
Depends.. I would try to load into a string, then do a explode() with newline, so it's in array, then run a foreach with a skip on any that doesnt have strpos == 0 -AND- strpos !== false, you can put in a continue to skip to the next line if it doesnt match.
Another option, is to parse, and skip, or even using fseek, and such. Depends on alot of different factors to determine whats going to be fastest.
You can implode later on, and add the newlines back in, and then push out a file, and/or use line breaks. Depending where the output is supposed to go.
I think you gave the answer yourself:
Make a script that reads the input file line by line in a loop (while). It writes every line into an output file if two conditions are met: 1. a flag ("done") is FALSE and 2. the line does NOT start with ";;; " (not the blank). This removes those lines starting with three semicolons. Once you come about a line containing more semicolons you set the flag to TRUE, thus the remaining lines wil be copied without being examined.

re writing or formatting contents in .txt file to add numbering in front and semi colon at the end

I have a .txt file with content(see first image) I need the content in such a way that It should be numbered and comma at the end of every line(see second image).
I want to insert say: "1"=>" in front of the first line. The numbering will increase on the second line so having about 4747 lines the last number will be 4747.
then insert: ", at the end of every line.
I have some knowlege in PHP so if somebody has solution or idea that will be helpful. I have been formatting this manually and that is very time consuming
Using PHP:
open your original file (consider fopen() or file_get_contents)
Split into an array by newline (explode())
process array line by line (for or foreach)
prepend the current line number
append quote and comma
loop to next array member
When finished - save content to file (file_put_contents())
That should be enough for you to work it out for yourself!
Use PHP's file(), which will give you an array with one element for each line. After that it should be a simple matter of iterating over the array with foreach and concatenating the appropriate bits onto the string. Then use fopen() and fwrite() to write the edited lines to your output file.

Remove extra comma after string

I have a lot of data in a CSV file. I wrote some code to extract only column 1 and put it in a txt file:
fwrite($file2, $data[0].',');
Now, this created a TXT file with all values separated by a comma.
However, after the last value was read there was an extra comma
I don't need this, because when I used foreach($splitcontents as $x=> $y) using a comma delimiter, it reads a garbage value at the end because of the extra comma.
How do I remove or avoid the comma at the end?
Use fputcsv() instead of misreimplementing it.
Instead of assembling the CSV file yourself field-wise you could use fputcsv() which puts it into the right format:
while (...) {
fputcsv($file2, array($data[0], $data[1], $data[22]) );
The second parameter must be an array. If you really only want one column, then leave out the rest.
Also for reading the files back in, check out fgetcsv(). This might simplify your foreach + $splitstring approach.
One way to solve the problem is to use rtrim($data, ',') on the data you load from the second file before splitting it. This will remove the trailing comma.
If you want to fix the file itself, you can do this:
ftruncate($file2, ftell($file2)-1);
You have to do this just before you call fclose()

Categories