I've a string like below
$num = "20142311.235504";
I want to split the string in below format
$date['year'] = 2014;
$date['Month'] = 23;
$date['day'] = 11;
$date['hour'] = 23;
$date['min'] = 55;
$date['sec'] = 04;
or even in date form like below
2014/23/11 23:55:04
I tried using preg_split('/(d{4})/',$num,$matches); and str_split but am not getting the desired output. Your help is highly appreciated.
If the string is a date, you can do this :
$num = "20142311.235504";
// You create a date with your string according to your current format
$date = date_create_from_format("Ydm.His", $num);
// Now you can play with it
$formattedDate = $date->format("Y/d/m H:i:s"); // `string(19) "2014/23/11 23:55:04"`
$dateTest['year'] = $date->format("Y"); // 2014
$dateTest['Month'] = $date->format("m"); // 11
$dateTest['day'] = $date->format("d"); // 23
$dateTest['hour'] = $date->format("H"); // 23
$dateTest['min'] = $date->format("i"); // 55
$dateTest['sec'] = $date->format("s"); // 04
Demo here : http://sandbox.onlinephpfunctions.com/
With the help of regex you can do this. In pattern create capture group for garbing year, months, days, hours, minutes and seconds. Simple example:
$str = "20142311.235504";
preg_match('~^(?<year>\d{4})(?<day>\d{2})(?<month>\d{2}).(?<hour>\d{2})(?<minute>\d{2})(?<second>\d{2})$~', $str, $match);
echo '<pre>', print_r($match);
But I prepare you to use date_create_from_format() which is more easier and faster than regex. First, convert a known date format separated by -, explode that format to convert an array and finally assign the array to a set of key [by array_combine()]. Example:
$str = "20142311.235504";
$match = array_combine(['year', 'month', 'day', 'hour', 'minute', 'second'], explode('-', (date_create_from_format("Ydm.His", $str))->format('Y-m-d-H-i-s')));
echo '<pre>', print_r($match);
Related
how can I get range for bottom string in php?
M0000001:M0000100
I want result
M0000001
M0000002
M0000003
..
..
..
M0000100
this is what i do
<?php
$string = "M0000001:M0000100";
$explode = explode(":",$string );
$text_one = $explode[0];
$text_two = $explode[1];
$range = range($text_one,$text_two);
print_r($range);
?>
So can anyone help me with this?
This is one of many ways you could do this and this is a little verbose but hopefully it shows you some "steps" to take.
It doesn't check for the 1st number being bigger than the 2nd.
It doesn't check your Range strings start with a "M".
It doesn't have all of the required comments.
Those are things for you to consider and work out...
<?php
$string = "M00000045:M000099";
echo generate_range_from_string($string);
function generate_range_from_string($string) {
// First explode the two strings
$explode = explode(":", $string);
$text_one = $explode[0];
$text_two = $explode[1];
// Remove the Leading Alpha character
$range_one = str_replace('M', '', $text_one);
$range_two = str_replace('M', '', $text_two);
$padding_length = strlen($range_one);
// Build the output string
$output = '';
for ( $index = (int) $range_one; $index <= (int) $range_two; $index ++ ) {
$output .= 'M' . str_pad($index, $padding_length, '0', STR_PAD_LEFT) . '<br>';
}
return $output;
}
The output lists a String in the format you have specified in the question. So this is based solely upon that.
This could undergo a few more revisions to make it more function like, as I'm sure some folks will pick out!
I have string '6m15s' in PHP that I would like to convert in to time or ideally seconds. I am using the strtotime() function like:
$time = date('H:i:s', strtotime('6m15s'));
echo $time;
But all I get '01:00:00'. Is this possible to convert my string and if so what would be the best way to do so?
You could use substr():
$string = '6m15s';
$minute = substr($string, 0, 1);
$second = substr($string, 2, 2);
echo date('H:i:s', strtotime("00:$minute:$second"));
// outputs 00:06:15
If you're trying to get the total number of seconds then something like:
preg_match('/((?<h>[\d]+)h)?((?<m>[\d]+)m)?((?<s>[\d]+)s?)/', $var, $m);
echo ($m['h']* 60 + $m['m']) * 60 + $m['s']; // 375
This looks for hours as well, as in 1h6m15s.
If you are working with the fix patterns then you can construct a method like:
function stringToSecondByPattern($subject, $pattern = '/(\d+)m(\d+)s/') {
$matches = [];
preg_match($pattern, $subject, $matches);
list($original, $minuets, $seconds) = $matches;
$secondsSum = $seconds + ($minuets * 60);
return $secondsSum;
}
print stringToSecondByPattern('6m15s');
In text, i have a lot of time number, then i want to change hour to another timezone (+6), example :
00:15 => 06:15
01:00 => 07:00
... and so on.
I'm trying this :
$result = str_replace(
array("00:","01:","02:","03:","04:","05:","06:","07:","08:","09:","10:","11:","12:","13:","14:","15:","16:","17:","18:","19:","20:","21:","22:","23:"),
array("06:","07:","08:","09:","10:","11:","12:","13:","14:","15:","16:","17:","18:","19:","20:","21:","22:","23:","00:","01:","02:","03:","04:", "05:"),
$text
);
echo $result;
But 18: will replace with 04: because php replace 18: to 22: then continue replace 22: to 04:
How to solved this, thank you.
// Edit : To #user3414969 and #Medda86: $text is the data i'm get from another site, that mean i can not control the source, only way to do is replace
// Edit 2 : Here is content : http://bongdatv.net/test.php
// Edit 3: Please solve this problem with replace way, not calculation number way.
I think best is to use the timestamp format, add the time and get out the new time from that.
http://php.net/manual/en/function.time.php
$time = array("00:","01:","02:","03:","04:","05:","06:","07:","08:","09:","10:","11:","12:","13:","14:","15:","16:","17:","18:","19:","20:","21:","22:","23:");
$required_time = array();
foreach($time as $t){
$hour = $t."00"; // 00 appending 0 minites
$hours_plus = 6; // adding 6 hours
$required_time[] = date('H:', strtotime($hour)+($hours_plus*60*60));
}
echo "<pre>";
print_r($required_time);
echo "</pre>";
Optimal way is as suggested by Medda86
However, you can try upon this way
$array = ("00:","01:",....);
//Then you can loop over array and add the time
for($i=0 ; $i < sizeof($array);$i++){
$array[$i] = intval($array[$i]+6)%24;
if($array[$i] < 10)
$array[$i] = str_pad($array[$i],2,'0',STR_PAD_LEFT).':';
else
$array[$i] .= ':';
}
Try this:
$yourArr = array('00:15','01:00','00:30');
foreach ($yourArr as $key => $value) {
$timestamp = strtotime($value) + 60*60*6; // add hours as per your need.
$time = date('H:i', $timestamp);
$newArr[] = $time;
}
echo "<pre>";
print_r($newArr);
Result is:
Array
(
[0] => 06:15
[1] => 07:00
[2] => 06:30
)
I have an array say:
array("10:10:20", "-20:00:10", "14:15:00", "08:10:00");
I tried using strtime but it is giving me error as it cant convert negative values to timestamp. Is there any another way?
After rereading the question I made a little snippet, the average is a sum of numbers. So i'm guessing this should be correct. To bypass the negative timestamps, you just need to calculate the absolute one, make it negative and add it to the sum.
<?php
$timings = array("10:10:20", "-20:00:10", "14:15:00", "08:10:00");
//$timings = array("-10:10:20", "-10:10:20", "-10:10:20", "-10:10:20");
$totalTime = 0;
foreach($timings as $timing) {
$isNegativeTime = strpos($timing, '-') !== false;
$time = strtotime(str_replace('-', '', $timing));
if ($isNegativeTime) $time *= -1;
$totalTime += $time;
}
$avgTiming = $totalTime / count($timings);
$isNegativeAvgTime = $avgTiming < 0;
$avgTiming = date('h:i:s', abs($avgTiming));
echo ($isNegativeAvgTime ? '-':'').$avgTiming;
<?php
$moredownvotes = array("10:10:20", "-20:00:10", "14:15:00", "08:10:00");
$nb_lol = count($moredownvotes);
for ($i = 0; $i < ($nb_lol - 1); ++$i)
{
$pattern = '/^-(.*)/';
$replacement = '${1}';
$moredownvotes[$i] = preg_replace($pattern, $replacement, $moredownvotes[$i]);
}
print "<pre>";
print_r($moredownvotes);
print "</pre>";
?>
Result :
Array
(
[0] => 10:10:20
[1] => 20:00:10
[2] => 14:15:00
[3] => 08:10:00
)
NOW u can use DateTime functions or w/e u want
$date = DateTime::createFromFormat('H:i:s', $moredownvotes[$i]);
echo date_format($date, 'H:i:s');
**RESULT ** : 10:10:20
PHP.net createFromFormat function
I have a php page listed below with events and I wish to order them by dates. No problem with this, but I want the date format was "15/Lug/1998" and not "15/Lug/1998:00:00:00 -0000". I post the code to fix this problem. Thanks in advance for your reply and help.
<?php
# For demo - some data that we will test with
$stuff = <<<COURSES
02 - - [15/Lug/1998:00:00:00 -0000] "Event01"
05 - - [21/Lug/1998:00:00:00 -0000] "Event02"
07 - - [16/Lug/1998:00:00:00 -0000] "Event03"
COURSES;
# Date in yukky format to Unix timestamp
function gdate($record) {
eregi('\[([0-9]{2})/([A-Z]{3})/([0-9]{4}):([0-9]{2}):([0-9]{2}):([0-9]{2})',
$record, $gotten);
$yikes = 1 + (strpos("GenFebMarAprMagGiuLugAgoSetOttNovDic",
$gotten[2]))/3; # Date "Alpha Triplet" to Month No.
$when = mktime($gotten[4],$gotten[5],$gotten[6],
$yikes,$gotten[1],$gotten[3]);
return $when;
}
function bydate($left,$right) {
$whenone = gdate($left);
$whentwo = gdate($right);
if ($whenone == $whentwo) return 0;
return (($whenone < $whentwo) ? -1 : +1);
}
$records = explode("\n",$stuff);
sort ($records);
$result = implode("<br />",$records);
print "<hr> Normal sort</br>$result";
usort ($records,bydate);
$result = implode("<br />",$records);
print "<hr> User defined sort - by date stamp</br>$result";
?>
Your timestamp is generated through below code
function gdate($record) {
eregi('\[([0-9]{2})/([A-Z]{3})/([0-9]{4}):([0-9]{2}):([0-9]{2}):([0-9]{2})',
$record, $gotten);
$yikes = 1 + (strpos("GenFebMarAprMagGiuLugAgoSetOttNovDic",
$gotten[2]))/3; # Date "Alpha Triplet" to Month No.
$when = mktime($gotten[4],$gotten[5],$gotten[6],
$yikes,$gotten[1],$gotten[3]);
return $when;
}
Modify it like below:
function gdate($record) {
eregi('\[([0-9]{2})/([A-Z]{3})/([0-9]{4}):([0-9]{2}):([0-9]{2}):([0-9]{2})',
$record, $gotten);
$yikes = 1 + (strpos("GenFebMarAprMagGiuLugAgoSetOttNovDic",
$gotten[2]))/3; # Date "Alpha Triplet" to Month No.
$time = mktime($gotten[4],$gotten[5],$gotten[6],
$yikes,$gotten[1],$gotten[3]);
$when = date('d/M/Y', $time); //this is solution one, recommended
$when = substr($time, 0, -15); //this is solution two
return $when;
}
EDIT:
Remain your previous code and modify below part:
$records = explode("\n",$stuff);
TO:
$rec = str_replace(":00:00:00 -0000", "", $stuff);
$records = explode("\n",$rec);
Second EDIT:
Change: (Change two places)
$result = implode("<br />",$records);
To:
$result = implode("<br />",str_replace(":00:00:00 -0000", "", $stuff));