What I'm attempting to do is create a simple "Quote of the Day" script. What this needs to do is be able to read from a simple .txt file, grab each entry per line and output the contents of that line, once per day. For example, if a .txt file had the following text:
This is the quote of the day
This is another quote of the day
This is the last quote of the day
Then, the script would grab the first block of text, This is the quote of the day and output it on the site. It would then cycle through, line by line, based on each incremental day until the end (and then cycle back to the beginning). Hopefully this would just allow people to cut/paste new info in as it would rely on line numbers, not the content itself.
If anyone even knows of a .XML implementation of this - it would be a big help - trying to figure out the simplest way of going about this. Thanks!
Assuming you had a file with 365 lines (one line per the current day)...
$lines = file("quotes.txt");
$day = date("z");
echo $lines[$day];
You can save the current index line and day on the first line of the file, like this:
01;09-11-2011
This is the quote of the day
This is another quote of the day
This is the last quote of the day
To retrieve the quote you would check if the date is today, if it is you get the nth line otherwise you add 1 to the number, update the date and then get the quote.
This should work with any number of lines in your textfile (untested):
// get lines
$lines = file('lines.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
// snap to midnight
$day = mktime(0,0,0, date("n"), date("j"), date("Y")) / (3600*24);
// modulo fun
echo $lines[ $day % count($lines) ];
It's very simple.
1.) You create a text file with 7 lines, each line represents a quote.
2.) PHP: You have to load the file into an array and get the numeric representation of the current day of the week:
$quotes = file('your_file.txt');
$the_quote = $quotes[ date('w') ];
echo $the_quote;
From php.net:
w
Numeric representation of the day of the week
0 (for Sunday) through 6 (for Saturday)
If you want to have a quote for each day in a year, just create a file with 366 lines and use date('z').
The most flexible way is definitely:
$day = date("z");
$file = file('quotes.txt');
$file_length = count($file);
$quote = $file[$day % file_length];
By using the modulus of the day and file length you have a recurring cycle every day from the first line to the last line of the file (and then start again).
Related
In my folder cache, i have dozens of files whose name is filename-number.json, like
sifriugh-80.json
dlifjbhvzique-76.json
dfhgzeiuy-12.json
...
I have a simple script that cleans my cache dir every 2 hours, deleting files older than 2 hours:
$fileSystemIterator = new FilesystemIterator('cache');
$now = time();
foreach ($fileSystemIterator as $file) {
if ($now - $file->getCTime() >= 3 * 3600) // 2 hours
unlink('cache/' . $file->getFilename());
}
Now, i'm looking to only delete every 2 hours files whose number (before .json but not if number is present at the beginning of the file) does NOT end by -100.json, and those ending by -100.json, every 7 days only.
I know that i can use preg_match() to get names, but is there any effective way to perform it?
There is much simpler way than regex using PHP 8+ str_ends_with() : https://www.php.net/manual/en/function.str-ends-with.php
if (str_ends_with($file->getFilename(), '100.json)) {
// unlink at needed time
} else {
// unlink at needed time
}
For PHP 7, there are several ways to emulate it, check at the bottom of https://www.php.net/manual/en/function.str-ends-with.php
I do not see why you should not use preg_match. It is so good here.
Before using preg_match you should check the first symbol in file name and skip the next code if it is_numeric.
If it is not numeric you need to get only ending "-" can be presented zero or ones + number 1 or more digits + .json ending
(pattern can be something like this /-?\d+\.json$/)
After that you can parse it and know the real number before .json,
Your verification will be something like
If "-" symbol exists and number is 100 check the date for 7 days
If number is not 100 check the date for 2 hours
I'm simply trying to check if the time is either above 9am or below 6pm, the 6pm check works fine and displays the data where as 9am one does nothing but works when changed to 10am.
Here is the line of code I'm using
elseif ((($data[6]) < "09:00") || (($data[6]) > "18:00"))
{
$contact[] = $data;
}
So, let us assume that your time format is always hh:mm. You want to check if the time is between 9 and 18 hours. The problem in your code, as you described, comes when you are check again 09:mm. As it strips away the minute part and just compares the hours.
I would try something like this:
elseif ( implode("", explode(":", $data[6])) > 900 && implode("", explode(":", $data[6])) < 1800)
I will explain the approach step by step.
First of all, this code checks if the date is within the range of 09:00 to 18:00. The code you have provided tested if it is less than 9 or more than 18.
Let us focus on one part of the code, that will explain the whole thing as well:
implode("", explode(":", $data[6])) > 900
First, we separate hours and minutes using the explode function. This gives us an array with two values.
`[0] => hh,`
`[1] => mm`
Now that we have separated this value we implode or concatenate them using the implode function that has no separator.
Next, instead of testing against the string, we test against the number. 09:00 is the same as 900 in this case.
Thus, we can check if the time is within the required limits.
Of a given datetime I need the very end of the previous month.
For example:
$date_given = '2019-07-14 16:33:05';
should become:
2019-06-30 23:23:59
I have some possible solutions to make it in several lines. But the requirement for my program/script is to have it in one line. So something like this:
$date_result = ...somefunction..(($date_given) -1 month) ...;
It really would be helpfull to have everything in that one line and not have prior lines with functions.
Thanks.
Here is many solution to this, but if has to be one line i would go with this
echo date_create($date_given.' last day of last month')->format('Y-m-d 23:59:59');
I actually don't know if there is a a way to dynamically get the last hour/minute/second of a day but I guess we can safely assume it always is "23:59:59" so you could do:
$lastDateOfMonth = date("Y-m-t 23:23:59", strtotime($date_given . '- 1 month'));
I'm trying to make a simple function, that echos a random element from an array, but it should change, every time that day changes. Example:
$myarray = array(
'foo',
'bar',
'winnie',
'the',
'poo');
echo array_rand($myarray);
This would print a random thing from the array, every time the page loads. But I would like for it to only change each day. I would like for it to work, so if you load the page Monday at 8:00 and Monday at 17:00 (edit1: it's the same random output that has been pulled, regardless of, if it's user A or user B that sees it), then you would see the same (random) element, from the array. But if the page was loaded at Tuesday at 13:00, then a different element from the array would be printed. Edit1: The timezone should be the easiest to program (since it's not significant). So I assume that the servers timezone would be the easiest.
I thought about getting integer-value of the date, and then use modulo to the length of the array (since the length of the array will get more and more values with time). Something along the lines of echo $myarray[date(U) % count($myarray)] (this hasn't been tested and wont work, since it's the second since 1970 (or whenever) and not the days, but it was just to give an idea of what kind of solution I had in mind).
There is no database on the site, so I can't store the value in a database.
Edit2: So if we have user A and user B, that each load the page each day of the week. Then I'm looking for user A to receive something along these lines:
Monday: foo
Tuesday: the
Wednesday: foo
Thursday: poo
Friday: winnie
Saturday: winnie
Sunday: bar
And if user B load the page, then he will see the same values as user A (I assume this is the easiest way to set it up as well).
-- end of edit2 --
Edit3: It could also just be a txt-file or a json-file that is stored on the FTP-server, where each day, a new line of this txt-file is printed. It doesn't need to be an array.
-- end of edit3 --
You can do this with a simple text file on the server:
$randoms = array(
'foo',
'bar',
'winnie',
'the',
'poo'
);
$file = 'todaysrandom.dat';
if(file_exists($file) && date('d-m-Y', filemtime($file)) == date('d-m-Y')){
//if the file exists, and was last updated today, return the contents of the file:
$todaysRandom = file_get_contents($file);
}else{
//else create todays value, and save it to the file
$todaysRandom = $randoms[rand(0,count($randoms)-1)];
file_put_contents($file, $todaysRandom);
}
echo $todaysRandom;
I'm parsing subtitle files (srt format) and here's an example of a line of dialogue:
27
00:01:32,400 --> 00:01:34,300
Maybe they came back
for Chinese food.
The times come in the format
hours:minutes:seconds,milliseconds
I want to manipulate these times and do comparisons but the various PHP classes I've come across don't seem to have support for milliseconds.
My problem:
One thing I want to do is parse 2 subtitle files that are for the same piece of media (e.g. same film, or same TV episode, etc.) and compare each subtitle file's text for the same lines of dialogue. The problem is that the start and end times for the same lines will be slightly off by a few hundred milliseconds. For example, taking the line above, in another subtitle file the time for that same line is
00:01:32,320 --> 00:01:34,160
To get both files' versions of the same line of dialogue, you could check to see if there is a line in file two that is within a few hundred milliseconds of file one's start and end times, and that should catch it. Something like that. So I need to manipulate times by adding milliseconds to them and also do comparisons of those times.
Assuming you're on PHP >=5.3 (required for getTimestamp()), this will work:
$unformatted_start = '00:01:32,400';
$unformatted_end = '00:01:34,300';
// Split into hh:mm:ss and milliseconds
$start_array = explode(',', $unformatted_start);
$end_array = explode(',', $unformatted_end);
// Convert hh:mm:ss to DateTime
$start = new DateTime($start_array[0]);
$end = new DateTime($end_array[0]);
// Convert to time in seconds (PHP >=5.3 only)
$start_in_seconds = $start->getTimestamp();
$end_in_seconds = $end->getTimestamp();
// Convert to milliseconds, then add remaining milliseconds
$start_in_milliseconds = ($start_in_seconds * 1000) + $start_array[1];
$end_in_milliseconds = ($end_in_seconds * 1000) + $end_array[1];
// Calculate absolute value of the difference between start and end
$elapsed = abs($start_in_milliseconds - $end_in_milliseconds);
echo $elapsed; // 1900
Did you try strtotime?
if (strtotime($date1) > strtotime($date2)) { # date1 is after date2
# do work here
}
if (strtotime($date1) < strtotime($date2)) { #date2 is after date1
# do other work here
}