what I'm trying to do looks impossible with my actual PHP skills. Below you can find an exemple of a race result file, in txt. This file is composed of :
dir= the-track-file-name
longname= the-track-long-name-with-spaces
firstlap= the number of gate (checkpoint) the first lap is composed of
normallap= the number of gate (checkpoint) other laps are composed of
holeshotindex= thefirst gate after the start, which determine which player started first
time= the race duration, in minutes
laps= the number of laps (if minutes + laps, laps are counted when time's up)
starttime=1793
date= timestamp of the start
players:(under this line are all the player, just 1 in this exemple)
slot=0 (this is the multiplayer server slot taken by the player)
uid=5488 (this is the unique ID of the player)
number=755 (player's race number)
bike=rm125 (player's motorbike model)
name=Nico #755(player's name)
times: (under this line are things like timestamps of every gate, like SLOT|GATE|TIME)
0 0 1917 (it's like divide the timstamp /128 sounds good)
0 1 2184
(and etc, see full exemple below...)
The game server is on a dedicated ubuntu.
At each race end I send these results on an FTP web server, and what I need is to get vars to output something readable like a table with results after selecting a race (in a dropdown list i.e.).
Doing the table isn't the problem.
My problem is, even searching a lot here, that I don't know how to read the txt to obtain this kind of page (only RESULTS table) : http://mxsimulator.com/servers/q2.MXSConcept.com/races/6015.html
Here is a full sample result file : http://www.mediafire.com/view/3b34a4kd5nfsj4r/sample_result_file.txt
Thank you
Ok, tonight it's file parsing time.
I've written a very basic parser, which walks through the data line by line.
First it looks for "=". When a "=" is found the line is split/exploded at "=".
You get two parts: before and after the "=".
I've used them as key and value in an $results array.
This process continues till we reach the line "times:".
That's the line indicating that on the next line (line "times:" + 1) the results start.
The results are "slot gate time" separated by spaces. So the results are exploded with " " (space) this time and you get the three parts.
I've inserted an array key 'times' which contains an array with named keys (slot,gate,time).
You might just look at the structure of the $results array.
It should be very easy to iterate over it to render a table or output data.
#$datafile = 'http://www.mediafire.com/view/3b34a4kd5nfsj4r/sample_result_file.txt';
#$lines = file_get_contents($datafile);
$lines = '
dir=Dardon-Gueugnon
longname=Dardon Gueugnon
firstlap=72
normallap=71
holeshotindex=1
time=0
laps=6
starttime=1846
date=1407162774
players:
slot=0
uid=8240
number=172
bike=rm125
name=Maximilien Jannot | RH-Factory
slot=1
uid=7910
number=666
bike=rm125
name=Patrick Corvisier|Team RH-Factory
slot=2
uid=10380
number=114
bike=rm125
name=Benoit Krawiec | MXS-Concept.com
slot=6
uid=6037
number=59
bike=rm125
name=Yohan Levrage | SPEED
slot=8
uid=6932
number=447
bike=rm125
name=Morgan Marlet | Mxs-Concept.com
times:
6 0 1974
1 0 1989
0 0 2020
2 0 2056
6 1 2242
1 1 2260
0 1 2313
2 1 2338
6 2 2434
1 2 2452';
$results = array();
$parseResults = false;
#foreach($lines as $line){ // use this line when working with file_get_contents
foreach(preg_split("/((\r?\n)|(\r\n?))/", $lines) as $line){
if($parseResults === true) {
$parts = explode(' ', $line); // SLOT|GATE|TIME = parts 0|1|2
$times = array(
'slot' => $parts[0],
'gate' => $parts[1],
'time' => $parts[2]
);
$results['times'][] = $times;
}
if(false !== strpos($line, '=')) { // if line has a = in it, explode it
$parts = explode('=', $line);
$results[$parts[0]] = $parts[1]; // assign parts to array as key=value
}
if(false !== strpos($line, 'times:')) {
// we reached "times:", let's set a flag to start reading results in the next iteration
$parseResults = true;
}
}
var_dump($results);
Output:
array(15) {
["dir"]=> string(15) "Dardon-Gueugnon"
["longname"]=> string(15) "Dardon Gueugnon"
....
["name"]=> string(31) "Morgan Marlet | Mxs-Concept.com"
["times"]=> array(10) {
[0]=> array(3) { ["slot"]=> string(1) "6" ["gate"]=> string(1) "0" ["time"]=> string(4) "1974" }
[1]=> array(3) { ["slot"]=> string(1) "1" ["gate"]=> string(1) "0" ["time"]=> string(4) "1989" }
[2]=> array(3) { ["slot"]=> string(1) "0" ["gate"]=> string(1) "0" ["time"]=> string(4) "2020" }
...
} } }
Related
I have column named ID and I want it to indicate year that record when it was created with format.
Scenario
I created new data on this day( 1-11-2019) and with the format.
2019-01-110000-1
And when it is reached to 9 it will become 0000-00010
Example:
20190101-0000-0001
...
20190101-0000-0010
View
<?= $purchase_order->date . sprintf("%06s",-$counter) ?>
Question: How can I add leading zeroes in 0000-1(it should be like this 0000-0001 and when it reached 9 it will become 0000-0010
Math.
function weirdNumberFormatter(int $input) {
$high = intdiv($input, 10000);
$low = $input % 10000;
return sprintf('%04d-%04d', $high, $low);
}
var_dump(
weirdNumberFormatter(1),
weirdNumberFormatter(1234),
weirdNumberFormatter(12345),
weirdNumberFormatter(1234567),
weirdNumberFormatter(12345678)
);
Output:
string(9) "0000-0001"
string(9) "0000-1234"
string(9) "0001-2345"
string(9) "0123-4567"
string(9) "1234-5678"
I am trying to create a project which will help students study various areas. The idea is that I have a piece of raw text, which contains quiz questions and answers which I want to parse as question header and answer options, which will be inserted into a database. However, the text is not properly formatted and due to the large amount of questions and answers (around ~20k per total), I cannot afford the time to manually insert them or format the text myself.
The raw text looks like this:
1. A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles?
a) $44.44 b) $109.08 c) $118.80
d) $408.04 e)
$444.40
2. When x = 3 and y = 5, by how much does the value of 3x2 – 2y exceed the value of 2x2 – 3y ?
a) 4
b) 14
c) 16
d) 20 e) 50
I tried creating my own PHP functions to parse the text properly, however I cannot get myself to get past the random line breaks, spaces, etc.
What I am trying to obtain:
array(1) {
[0]=>
array(3) {
["questionNumber"]=>
string(1) "1"
["questionText"]=>
string(175) "A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles?"
["options"]=>
array(5) {
["a"]=>
string(6) "$44.44"
["b"]=>
string(7) "$109.08"
["c"]=>
string(7) "$118.80"
["d"]=>
string(7) "$408.04"
["e"]=>
string(7) "$444.40"
}
}
}
The code I have so far:
$rawText = '1. A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles?
a) $44.44 b) $109.08 c) $118.80
d) $408.04 e)
$444.40
2. When x = 3 and y = 5, by how much does the value of 3x2 – 2y exceed the value of 2x2 – 3y ?
a) 4
b) 14
c) 16
d) 20 e) 50
';
$rawTextLines = explode("\n", $rawText);
foreach ($rawTextLines as $lineNumber => $lineContents) {
$lContents = trim($lineContents);
if (empty ($lContents)) {
unset ($rawTextLines[$lineNumber]);
} else {
$rawTextLines[$lineNumber] = $lContents;
}
}
$processedQuestions = array ();
$currentQuestionHeader = 0;
foreach ($rawTextLines as $lineNumber => $lineContents) {
if (ctype_digit(substr($lineContents, 0, 1))) { // Question header
$questionHeaderInformation = explode('.', $lineContents);
$currentQuestionHeader = $questionHeaderInformation[0];
$processedQuestions[$currentQuestionHeader]['questionNumber'] = $currentQuestionHeader;
$processedQuestions[$currentQuestionHeader]['questionText'] = $questionHeaderInformation[1];
} else { // Question option
$options = explode(')', $lineContents);
if (count ($options) % 2 === 0) {
$processedQuestions[$currentQuestionHeader]['options'][trim($options[0])] = ucfirst(trim($options[1]));
} else {
}
}
}
Which produces this:
array(2) {
[1]=>
array(3) {
["questionNumber"]=>
string(1) "1"
["questionText"]=>
string(35) " A car averages 27 miles per gallon"
["options"]=>
array(1) {
["a"]=>
string(8) "$44.44 b"
}
}
[2]=>
array(3) {
["questionNumber"]=>
string(1) "2"
["questionText"]=>
string(96) " When x = 3 and y = 5, by how much does the value of 3x2 – 2y exceed the value of 2x2 – 3y ?"
["options"]=>
array(3) {
["a"]=>
string(1) "4"
["b"]=>
string(2) "14"
["c"]=>
string(2) "16"
}
}
}
As you can see, the current output does not match - not by far, what I am trying to obtain.
Thank you in advance.
Hellow,
^[0-9]+\. (.*)[\r\n]+a\)[\s]+(.*)[\s]+b\)[\s]+(.*)[\s]+c\)[\s]+(.*)[\s]+d\)[\s]+(.*)[\s]+e\)[\s]+(.*)[\s]*
Try it !
$re = '/^[0-9]+\. (.*)[\r\n]+a\)[\s]+(.*)[\s]+b\)[\s]+(.*)[\s]+c\)[\s]+(.*) [\s]+d\)[\s]+(.*)[\s]+e\)[\s]+(.*)[\s]*/m';
$str = '1. A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles?
a) $44.44 b) $109.08 c) $118.80
d) $408.04 e)
$444.40
2. When x = 3 and y = 5, by how much does the value of 3x2 – 2y exceed the value of 2x2 – 3y ?
a) 4
b) 14
c) 16
d) 20 e) 50';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
I have a txt file which contains data pertaining to hourly wind parameters for a particular date see this link for file
http://dropcanvas.com/04o06
In this the first hour data, that is 00:00:00 hrs is from line no. 3 to 30. I want date and time from 3rd line, stability class value in parenthesis from 5th line and wind speed and direction from 5th and 6th column of 12th line. I know how to get data and I coded in this way.
<?php
$file_handle = fopen("201017.dat", "r");
$line_no=0;
while (!feof($file_handle)) {
$line = fgets($file_handle);
$line_no++;
if($line_no==3 ){
$data=explode("\t",$line);
$date=$data[0];
$time=date('H:i:s',strtotime($data[1]));
}
if ($line_no==5 ) {
preg_match('/(?<=\()(.+)(?=\))/is', $line, $match);
$stability= $match[0];
}
if ($line_no==12 ) {
$data=explode("\t",$line);
$speed= $data[4];
$dir= $data[5];
}
}
$values[]="('$date', '$time',$dir,$speed,'$stability')";
Now the next hour data I need to push into array is from line no. 31,33 and 40. I can use if....else if for the entire 24 blocks of data which I feel is a cumbersome procedure. Is there a way to simplify this given the the line numbers are in arithmetic progression with a common difference of 28
$arr = file('201017.dat'); // read the whole file into array
/* NOTE! The whole file will be loaded into RAM,
so take into account ram restrictions for big files.
In this case 90kb is very small size */
$n = count($arr);
/* start with 2, because array indexes start with 0,
so the 3rd line will have index 2.
On the next interation $i will be 30 (that is 31th line,
$i+2 will be 33th line, $i+9 will be 40th line, etc.) */
for ($i = 2; $i < $n; $i += 28)
{
$data=explode("\t", $arr[$i]);
$date=$data[0];
$time=date('H:i:s',strtotime($data[1]));
preg_match('/(?<=\()(.+)(?=\))/is', $arr[$i+2], $match); // i+2 gives 5th line
$stability= $match[0];
$data=explode("\t", $arr[$i+9]);
$speed = $data[4];
$dir = $data[5];
$values[]="('$date', '$time',$dir,$speed,'$stability')";
}
var_dump($values);
/*
Shows:
[0]=>
string(52) "('10/20/2017', '00:00:00', 220.00, 1.39,'D')"
[1]=>
string(52) "('10/20/2017', '01:00:00', 215.00, 0.15,'E')"
[2]=>
string(52) "('10/20/2017', '02:00:00', 199.00, 0.95,'D')"
[3]=>
string(52) "('10/20/2017', '03:00:00', 203.00, 1.03,'D')"
..... etc.
*/
Currently I'm trying to extract data from a text file that generated from a .asp website that will be load into interface.txt file. Format of the data are below (All the name in the text has been masked):
format of data in text file split by comma
801B,SAMPING,VAC,25999,2,R**NA** B**T* A** R*H** ,FEMALE,2017-05-29, ,14:58:01.8000000
820A,SAMPING,VAC,11191,5,M**A*M** H*I**L B** K*M**R*LBA**R*N ,MALE,2017-05-31, ,20:33:19.0300000
505,SELENDANG,OCC,26194,2,I*F** *MR** B** M**D H**A* *AK*R**D** ,MALE,2017-06-01, ,17:49:54.6530000
810,SAMPING,VAC,14251,6,P**I** B**T* S*L**H ,FEMALE,2017-05-29, ,00:10:47.8630000
602B,SUTERA,OCC,26172,2,G**R*E C**E K** Z** ,MALE,2017-06-01, ,15:22:18.9970000
By using below codes, I'm trying to extract the data:
$file = "C:/btemp/bed-interface.txt";
$fileToLoad = fopen($file, "rb");
while(!feof($fileToLoad)){
$data = fgets($fileToLoad);
$extract = array_map('trim', explode(',', $data));
$bnum = trim(preg_replace('[^\s]', '', $extract[0]));
//other array continue here
}
fclose($fileToLoad);
Above codes will split the string by using comma but then when I'm trying to check each array strlen return, it will shows the incorrect value. For example, the first row data when return the $bnum it will show strlen of 7 instead 4. This will continue to other data. Can refer to below image to see the result of each return character. Each length are is in bracket. (All the name in the text has been masked)
801B (7) SAMPING (13) O 25999 (9) 2 (1) R**NA** B**T* A** R*H** (45) F 2017-05-29 (19) 14:58:01 (15)
820A (7) SAMPING (13) O 11191 (9) 5 (1) M**A*M** H*I**L B** K*M**R*LBA**R*N (69) F 2017-05-31 (19) 20:33:19 (15)
505 (5) SELENDANG (17) O 26194 (9) 2 (1) I*F** *MR** B** M**D H**A* *AK*R**D** (73) F 2017-06-01 (19) 17:49:54 (15)
810 (5) SAMPING (13) O 14251 (9) 6 (1) P**I** B**T* S*L**H (37) F 2017-05-29 (19) 00:10:47 (15)
602B (7) SUTERA (11) O 26172 (9) 2 (1) G**R*E C**E K** Z** (37) F 2017-06-01 (19) 15:22:18 (15)
Result of explode and length of each array return
So, how to prevent this to happen. How to remove all the space. Already tried using trim, array_map, preg_replace still space appear when count using strlen. Even to do match in mysql query, it will return false cause the space has made the query return false.
After investigating the value that has been sent to the database, seems that all the character in the database has unknown character after every each value.
For example SAMPING = S□A□M□P□I□N□G□ (there will be □ as unknown char and will read by strlen as 14 character)
By using correct preg_replace for each array retrieve:
$bnum = preg_replace('/[^A-Za-z0-9_ -]/','',$extract[0]);
instead of this:
$bnum = trim(preg_replace('[^\s]', '', $extract[0]));
it will remove all unwanted unknown character in the array and will save the correct value to the database.
I tried making a script that could save all files from a webpage with a pattern in name to a server.
<?php
$base_url = "http://www.someurl.com/";
$sufix = ".jpg";
$id_start= "Name Numberstart"; //Picture 1
$id_end = "Name Numberend"; // Picture 235
$path_to_save = "filer/";
foreach(range($id_start, $id_end) as $id) {
file_put_contents($path_to_save.$id.$sufix, file_get_contents($base_url.$id.$sufix));
}
?>
If I only use id with numbers etc. 1-20 or 50 - 60 and so on, the script works perfectly. But when I have a name in front and white space, it doesn't seem to work. It just saves 1 file and stops.
According to php.net's description of range:
Character sequence values are limited to a length of one. If a length greater than one is entered, only the first character is used.
I take that to mean that
range("Name Numberstart", "Name Numbersend") == array("N");
And if we run php interactively, this is confirmed:
php > $var = range("Name Numberstart", "Name Numbersend");
php > var_dump($var);
array(1) {
[0]=>
string(1) "N"
}
So basically, you're actually getting the range of the first character of the first word to the first character of the second word. If we change the second word to "Pretty", we get:
php > var_dump(range("Name Numberstart", "Pretty Numbersend"));
array(3) {
[0]=>
string(1) "N"
[1]=>
string(1) "O"
[2]=>
string(1) "P"
}