I have images and videos from my camera which are uploaded to my server. In order to properly organize them I need to extract the year month and day. But I cant seem to get this pregmatch right..
Input would be 20211215_083437.jpg
Output would be Year2021 Month11 Day15
if (preg_match('/^(\d{4})(\d{2})(\d{2})$/', $value, $matches)) {
$year = $matches[0];
$month = $matches[2];
$day = $matches[3];
You need to remove the $ anchor in your RegEx to make it work: it matches the end of the string but yours has content after the date.
Also, the year is the 1st capture group. The index 0 contains the complete matching string.
if (preg_match('/^(\d{4})(\d{2})(\d{2})/', $value, $matches)) {
$year = $matches[1];
$month = $matches[2];
$day = $matches[3];
}
But, using a regex for this is overkill. You could sustract the date part of the filename and create a DateTime object from it:
$date_string = substr($value, 0, 8);
$date = \DateTime::createFromFormat('Ymd', $date_string);
// Format the date as you want
echo $date->format('Y-m-d');
With DateTime::createFromFormat the expression can be completely parsed. substr is not needed. The expression after the underscore stands for a time I think.
$str = '20211215_083437.jpg';
$dt = DateTime::createFromFormat('Ymd_His.???', $str);
var_dump($dt);
//object(DateTime)#2 (3) { ["date"]=> string(26) "2021-12-15 08:34:37.000000" ..
echo $dt->format('\Y\e\a\rY \M\o\n\t\hm \D\a\yd');
Related
I need to pull the date and time out of this string: some_report_20161005_1530.xml so I can reformat it to something more work-with-able. The date and time will change from file to file, but will always stay in this format: some_report_{year}{month}{day}_{24hr time}.xml
$test = 'some_report_20161005_1530.xml';
preg_match('(\d{4})(\d{2})(\d{2})_(\d{4})', $test, $test_matches);
print_r( $test_matches );
What would be the best way to accomplish this?
(Forgive my ignorance or misuse of these functions. I am by no means an expert)
If the some_report doesn't contain digits, the date and time parts are already in a good order to work in the DateTime constructor, so you can extract them with a simpler regex.
$date_time = new DateTime(preg_replace("/[^0-9]/", "", $your_string));
One simple regex approach would be to pull out the 8 and 4 digit numbers:
preg_match("/(\d{8})_(\d{4})/", $filename, $matches);
array_shift($matches);
list($date, $time) = $matches;
Working example: https://3v4l.org/npGC8
Or you could just use explode and skip the regex:
list($name1, $name2, $date, $time) = explode("_", str_replace(".","_", $filename));
Working example: https://3v4l.org/lAvTN
Then it's as simple as handing it to DateTime, such that you can manipulate or format however you want.
$dt = new DateTime($date . $time);
echo $dt->format('n/j/y h:ia'); // 10/5/16 03:30pm
$test = 'some_report_20161005_1530.xml';
echo preg_replace('#(\d{4})(\d{2})(\d{2})(_)(\d{2})(\d{2})#',
'${1}-${2}-${3}_${5}:${6}', $test) , '<br/>';
preg_match(
'#(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})(_)(?<hour>\d{2})(?<minute>\d{2})#',
$test,$test_matches);
print_r( $test_matches );
Just examples...
I would like to know how can I take a character out of a string?
I have a date:
$date = "04.08.2013";
I would like to take just the first 2 zeros off. Like that:
$date = "4.8.2013"
How can I do it?
A simplish (read: hacky) solution would be:
$date = implode('.', array_map(function($x) { return (int)$x; }, explode('.', $date)));
You can may also get it done quickly using a regex:
$new_date = preg_replace('/(?<=^|\.)0/', '', $date);
Or more simply without the lookbehind (thanks #IlmariKaronen):
$new_date = preg_replace('/\b0/', '', $date);
Demo
use explode() to separate the string into an array then use ltrim to delete "0"
i.e.
$date = explode(".", "04.08.2013");
$new_date = implode(".", array(ltrim($date[0],"0"), ltrim($date[1],"0"), $date[2]));
or something like that
Hello I have this string that will generate the time that I then insert in the db
$time=mktime(date('G'),date('i'),date('s'));
$NowisTime=date('Gis',$time);
Now I need to readd colons to this string: :
I need it to be generated and inserted without colons, but shown in another place with colons reinserted, so that it will look like this:
13:24:09
Instead of:
132409
The same is for $todaydate = date('Ymd');
That should become then 2011-06-16
How can I do that?
Counting the words is not good, since we can have more or less types depending by the actual time and date.
Please advise
Thank you!
FOR WHO DOES NOT UNDERSTAND: this values are taken from the DB so I cannot use : date('Y-m-d'); in a values taken from the db........
The same is for $todaydate =
date('Ymd');
That should become then 2011-06-16
For this one, try :
date('Y-m-d');
Similar for your Other part.
Edit ::
For Date :
$time = "time from database";
$unixtimestamp = strtotime ( $time) ;
$date = date('Y-m-d', $unixtimestamp);
For time :
$time = strtotime("time from database");
$yourtime = date("H:i:s", $time);
The strings you supply for formatting can contain anything you'd like, so putting the dashes or semicolons there is no problem. You can even include other text, as long as any letters used in the date code are escaped with a backslash.
The entire
$time=mktime(date('G'),date('i'),date('s'));
$NowisTime=date('Gis',$time);
could be rewritten, too. You're maing a timestamp from the current time, then giving it to date(). date uses the current time by default, so there's no need to do that to show the current time.
Here's one way:
$NowisTime=date('G:i:s');
If you are doing exactly what you say you are doing, you can count the characters starting at the end and add the characters (: and -) at the right place:
Both date('is') and date('Ymd') produce a fixed format using leading zeros so the length is always the same. You only have to compensate for the date('G') part.
So really all you have to do is chop off 2 characters from the end of the string twice and what remains is the year or the hour.
Well if you use date('his') instead and cast it as a string (so PHP doesn't interpret it as an integer and remove the possible leading zero), you can add colons by splitting the string every two numbers and then imploding it with colons.
$d = (string)date( 'his' );
echo (int)$d; //Format without colons
echo implode( ':', array_map('intval', str_split( $d, 2 ) ) );
For the second part, do the same except split the string by 4 characters and then split the second split by 2.
$d = date('Ymd');
echo $d; //Format without dashes
list($year, $second) = str_split( $d, 4 );
$parts = str_split( $second );
array_unshift( $parts, $year );
echo implode( '-', $parts );
In both situations however it would just be easier to start out with the formatted strings (with the colons and dashes) and remove them for the db.
$d = date('G:i:s');
echo $d; //With colons
echo str_replace( ':', '', $d );
$d = date('Y-m-d');
echo $d; //With dashes
echo str_replace( '-', '', $d );
When you are generating the value to store in your database, use a Unix timestamp:
$timestamp = time();
// store $timestamp in your database
That way you don't have to worry about how it looks or parsing it at all. Then, when you're ready to display it to your user, you can use:
$formattedTime = date('G:i:s', $timestamp);
which will display it in the colonated (is that even a word?) format for your users.
Couldn't you do something like :
$new = "";
for ($i = 2; $i <= strlen($NowisTime); $i+2) {
$new .= $NowisTime[$i-2] . $NowisTime[$i-1] . ":";
}
$NowisTime=date('G:i:s',$time);
$todaydate = date('Y-m-d');
$date ='20101015';
how to convert to $year = 2010,$month = 10, $day =15
thanks
You can use the PHP substring function substr as:
$year = substr($date,0,4); # extract 4 char starting at position 0.
$month = substr($date,4,2); # extract 2 char starting at position 4.
$day = substr($date,6); # extract all char starting at position 6 till end.
If your original string as leading or trailing spaces this would fail, so its better feed substr trimmed input as. So before you call substr you can do:
$date = trim($date);
You can do it all in one go with
sscanf — Parses input from a string according to a format
Example:
list($y, $m, $d) = sscanf('20101015', '%4d%2d%2d');
or
sscanf('20101015', '%4d%2d%2d', $y, $m, $d);
You can use substring function
http://www.w3schools.com/php/func_string_substr.asp
$year=substr($date,0,4);
$month=substr($date,4,2);
$day=substr($date,6,2);
I am processing strings with a date somewhere in it. There are different ways the date can appear in this string:
"… 01.11.2009 18:00-21:00 …" or
"… 01.11.2009 18:00-02.11.2009 15:00 …" or
"… 01.11.2009 18:00 …"
Regardless how the date appears I only need the beginning date "01.11.2009 18:00". So if there are two matches it's just the first one. How can I isolate/explode this from the full string in php. any idea?
I guess I need to create a pattern with regex and then matching it with preg_match. Is this the way? Unfortunately I am not into regex very much. Could anyone help with getting my single date block from a random string?
$matches = array();
$desired_date = '';
preg_match('/\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}/', $string_containing_dates, $matches);
if (isset($matches[0])) $desired_date = $matches[0];
Try:
$s = "… 01.11.2009 18:00-21:00 …… 01.11.2009 18:00-02.11.2009 15:00 …… 01.11.2009 18:00 …";
preg_match_all('!(\d{2}\.\d{2}\.\d{4}) \d{2}:\d{2}(-\d{2}:\d{2}|-\d{2}\.\d{2}\.\d{4} \d{2}:\d{2})?!', $s, $matches);
print_r($matches[1]);
if your date is formatted in the following manner you will always have the same number of characters for each date. You could then use a simple substr() to take the beginning X chars:
// example date strings
$date = date('m.d.Y h:i:S');
$date2 = date('m.d.Y h:i:S', strtotime('+50 days'));
$date_str = $date . '-' . $date2;
// get the first 10 characters for the date
$match = substr($date_str, 0, 10);
Try this one:
preg_match_all(
'/([0-9]{2}\.[0-9]{2}\.[0-9]{4} [0-9]{2}:[0-9]{2})' // linebreak added
. '(?:-(?:[0-9]{2}\.[0-9]{2}\.[0-9]{4} )?(?:[0-9]{2}:[0-9]{2})?)?/',
'" 01.11.2009 18:00-21:00 " or " 01.12.2009 18:00-02.12.2009 15:00 " '
. 'or " 01.01.2009 18:00 "',
$matches
);
print_r($matches[1]);
// "01.11.2009", "01.12.2009", "01.01.2009"
You can extract the first date in that format using the function below:
function find_date($string) {
preg_match("/\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}/",$string,$matches);
return $matches[0];
}