Split numbers and words from user supplied data - php

I have the following code on my index.php file
<?php
$string = $_GET['string'];
$month = '';
$day = '';
?>
If string is like "apr12" or "12apr",
then $month should be "apr" and $day should be "12"
else both $month & $day should be blank.

You can use the fact that day is only numbers and month is only chars, so it may look like this:
$string = $_GET['string'];
$month = strtolower(preg_replace('/[^a-z]+/i','',$string));
$day = preg_replace('/[^0-9]+/','',$string);
if (!in_array($month, ['jan'/* ... and other valid values */], true)) {
$month = '';
}
if ($day === '' || (int)$day < 1 || (int)$day > 31) {
$day = '';
}
// Then validate your input further

Related

Start counting weeks from specific month

Im trying to write php code which would start counting weeks from specific month. For me its September and February. For example desired result for 01.09.2017 would be Semester-1,Week-1. and for 04.09.2017 would be Semester-1,Week-2. I found similar topics here and here . But their output result is array, should i work with arreys here too ? I want to mention that I almost have zero expierence with php language.
This is what I have come up with so far:
<?php
$day = date("D");
$month = date("M");
if($month == 'Apr'||'Feb'||'Mar'||'May') {
print "Semester-2,";
}
else print "";
if($month == 'Sep'||'Oct'||'Nov'||'Dec') {
print "Semester-1,";
}
else print "";
if($month == 'Jan') {
print "Exams";
}
if($month == 'Jun') {
print "Exams,";
}
if($month == 'Jun') {
print "Exams,";
}
if($month == 'Jul'||'Aug') {
print "Summer Break,";
}
You could do something like this:
$month = date('n'); // Month number 1-12
if ($month >= 9 && $month <=12) {
$period = 'Semester-1';
$startWeek = date('W', strtotime(date('Y') . '-09-01'));
} elseif ($month >= 2 && $month <=5) {
$period = 'Semester-2';
$startWeek = date('W', strtotime(date('Y') . '-02-01'));
} elseif ($month == 1) {
$period = 'Exams';
$startWeek = date('W', strtotime(date('Y') . '-01-01'));
} elseif ($month == 6) {
$period = 'Exams';
$startWeek = date('W', strtotime(date('Y') . '-06-01'));
} elseif ($month == 7 || $month == 8) {
$period = 'Summer break';
$startWeek = date('W', strtotime(date('Y') . '-07-01'));
}
$currentWeek = date('W') - $startWeek + 1;
echo $period . ' ' . 'Week-' . $currentWeek;
After #Qirel comment, I thought of something like this, hope this helps :
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$month = date("M"); /* current month */
if (in_array($month, array("Sep", "Oct", "Nov", "Dec"))) { $myperiod = "Semester #1"; }
if (in_array($month, array("Feb", "Mar", "Apr", "May"))) { $myperiod = "Semester #2"; }
if($month == 'Jan') { $myperiod = "Mid-Exams #1"; }
if($month == 'Jun') { $myperiod = "Final-Exams #2"; }
if( ($month == 'Jul') || ($month == 'Aug') ) { $myperiod = "Summer break"; }
$today = date("Y-m-d"); /* or use your date from user data */
$date = new DateTime($today);
$week = $date->format("W"); /* use of PHP function 'date' to get week # */
$currentweek = "$week";
echo "[ Week # $week ]";
echo"You currently are in : $myperiod - $currentweek";
?>
This should give you what you need:
$semesters = array(
'Sep' => 'Semester-1',
'Oct' => 'Semester-1',
'Nov' => 'Semester-1',
'Dec' => 'Semester-1',
'Jan' => 'Exams',
'Feb' => 'Semester-2',
'Mar' => 'Semester-2',
'Apr' => 'Semester-2',
'May' => 'Semester-2',
'Jun' => 'Exams',
'Jul' => 'Summer Break',
'Aug' => 'Summer Break',
);
switch ($semesters[date('M')]) {
case 'Semester-1':
$sep1st = strtotime('2017-09-01');
$week1 = date('W', $sep1st);
$currentWeek = date('W');
echo 'Semester-1, Week-', $currentWeek - $week1 + 1; // +1 because the count starts at 1.
break;
case 'Semester-2':
$feb1st = strtotime('2018-02-01');
$week1 = date('W', $feb1st);
$currentWeek = date('W');
echo 'Semester-2, Week-', $currentWeek - $week1 + 1; // +1 because the count starts at 1.
break;
default:
echo $semesters[date('M')];
break;
}
Note that this can be refactored into smaller, more semantic parts.

Can I use an if statement with multiple conditions? PHP

I bet I can, but would it work like this?
function dutchDateNames($) {
$day = explode('-', $date)[2];
$dutchday = ($day < 10) ? substr($day, 1) : $day;
$month = explode('-', $date)[1];
if ($month == '01' . '02') {
$dutchmonth = 'Januari' . 'Februari';
}
$dutchdate = $dutchday . ' ' . $dutchmonth . ' ' . explode('-', $date)[0];
return $dutchdate
}
So, if $month is 01, $dutchmonth should be Januari. If $month is 02, $dutchmonth should be Februari, and so on.
I have the feeling I'm not doing this right?
Like thatyou would not return any month cause you concatenate (mounth 0102 does not exist).
If i correctly understand your question i think an array will be better :
$month = explode('-', $date)[1]; //Ok you use this data like an index
$letterMonth = ['01' => 'Januari', '02' => 'Februari', ....]; // Create an array with correspondance number -> letter month
$dutchmonth = $letterMonth[$month]; Get the good month using your index
Try this:
Use elseif conditions
if ($month == '01') {
$dutchmonth = 'Januari';
} elseif ($month == '02') {
$dutchmonth = 'Februari';
} elseif ($month == '03') {
$dutchmonth = '...';
}
Create lookup array and get value by key:
$month = '02';
$months = [
'01' => 'Januari'
'02' => 'Februari'
// more months here
];
$dutchmonth = isset($months[$month])? $months[$month] : '';
echo $dutchmonth;
I think the proper way is to save the map a array. Demo
<?php
$array['01'] = 'Januari';
$array['02'] = 'Februari';
print_r($array);
echo $array[$month];
You may do any of these:
if else
if ($month == "01") {
$dutchmonth = "Januari";
} else if($month == "02"){
$dutchmonth = "Februari";
}
switch
switch($month) {
case "01":
$dutchmonth = "Januari";
break;
case "02":
$dutchmonth = "Februari";
break;
}
Using array
$month_arr = array('01' => "Januari", '02' => "Februari");
$dutchmonth = $month_arr[$month];
NOTE: To use multiple if conditions use logical operators && or ||

Shows Call to a member function format() on boolean error in php after editing

Here is the original script
<?php
$monthToAdd = 36;
$d1 = DateTime::createFromFormat('Y-m-d', '2016-04-10');
$year = $d1->format('Y');
$month = $d1->format('n');
$day = $d1->format('d');
$year += floor($monthToAdd/12);
$monthToAdd = $monthToAdd%12;
$month += $monthToAdd;
if($month > 12) {
$year ++;
$month = $month % 12;
if($month === 0)
$month = 12;
}
if(!checkdate($month, $day, $year)) {
$d2 = DateTime::createFromFormat('Y-n-j', $year.'-'.$month.'-1');
$d2->modify('last day of');
}else {
$d2 = DateTime::createFromFormat('Y-n-d', $year.'-'.$month.'-'.$day);
}
$d2->setTime($d1->format('H'), $d1->format('i'), $d1->format('s'));
echo $d2->format('d-m-Y');
?>
and here is the one that I edited
<?php
$y = 2016;
$m = 04;
$d = 10;
$monthToAdd = 36;
$d1 = DateTime::createFromFormat('Y-m-d', '$y-$m-$d');
$year = $d1->format('Y');
$month = $d1->format('n');
$day = $d1->format('d');
$year += floor($monthToAdd/12);
$monthToAdd = $monthToAdd%12;
$month += $monthToAdd;
if($month > 12) {
$year ++;
$month = $month % 12;
if($month === 0)
$month = 12;
}
if(!checkdate($month, $day, $year)) {
$d2 = DateTime::createFromFormat('Y-n-j', $year.'-'.$month.'-1');
$d2->modify('last day of');
}else {
$d2 = DateTime::createFromFormat('Y-n-d', $year.'-'.$month.'-'.$day);
}
$d2->setTime($d1->format('H'), $d1->format('i'), $d1->format('s'));
echo $d2->format('d-m-Y');
?>
it give error
Idea is to add X value as month , show the result.
For example the date provided is "2016-04-10" and $monthToAdd = 4; , it should give a result of 2016-08-10
script was working , but I just want to add a form so that user can input month to calculate.
I am new to php, anyone help ?
In order for php to parse variables within stings properly, you must wrap them in double quote marks (").
Change
$d1 = DateTime::createFromFormat('Y-m-d', '$y-$m-$d');
to
$d1 = DateTime::createFromFormat('Y-m-d', "$y-$m-$d");
Try to change this
$d1 = DateTime::createFromFormat('Y-m-d', '$y-$m-$d');
to
$d1 = DateTime::createFromFormat('Y-m-d', "$y-$m-$d");
php won't parse values inside of ' but it will inside of "
Hope that helps, if not, could you please pass on the exact error, and the line that it references.

Php datetime function doesn't recognise dates before 1000

This code is used to take values inputted from a form but this does not take a year entered as 0100 as 0100 but as 1915, this is then used with the JS seen in one of my other questions any help here would be very good, I think the issue is something to do where the year is taken but I just can't get this to work correctly. Is this a limitation of php?
<?php
$year = "";
$month = "";
$day = "";
if (isset($_GET['year']) && !empty($_GET['year'])) {
$year = $_GET['year'];
}
if (isset($_GET['month']) && !empty($_GET['month'])) {
$month = $_GET['month'];
$monthNumber = date('m', strtotime("$month 1 Y"));
}
if (isset($_GET['day']) && !empty($_GET['day'])) {
$day = $_GET['day'];
}
if ($year != "" && $monthNumber != "" && $day != "") {
$fullUrlDate = $year . "-" . $monthNumber . "-" . $day;
$urlDate = new DateTime(date($fullUrlDate));
$today = new DateTime(date("Y-m-d H:i:s"));
$interval = $urlDate->diff($today);
$gapYears = $interval->y;
$gapMonths = $interval->m;
$gapDays = $interval->d;
$gapDaysTotal = $interval->days;
$gapWeeksTotal = round($interval->days/7);
$gapHours = $interval->h;
$gapMinutes = $interval->i;
$gapSeconds = $interval->s;
if ($gapWeeksTotal == 1) {
$gapWeeksSuffix = "";
} else {
$gapWeeksSuffix = "s";
}
if ($gapDays == 1) {
$gapDaysSuffix = "";
} else {
$gapDaysSuffix = "s";
}
$ordinalSuffix = date("S", strtotime($fullUrlDate));
if (strtotime($fullUrlDate) < strtotime(date("Y-m-d H:i:s")) ) {
$dateInThePast = true;
} else {
$dateInThePast = false;
}
// Months gap
$monthsInterval = date_diff($urlDate, $today);
$monthsGap = $monthsInterval->m + ($monthsInterval->y * 12);
$gapMonthsSuffix = ($monthsGap == 1 ? "" : "s");
DateTime has no such limitation, but the date function you use to initialise it, does. You can use DateTime::setDate to set any year you want:
php > $a = new DateTime("2015-08-24");
php > echo $a->format(DateTime::ISO8601);
2015-08-24T00:00:00+0000
php > $a->setDate(90, 8, 24);
php > echo $a->format(DateTime::ISO8601);
0090-08-24T00:00:00+0000
php > $a->setDate(90090, 8, 24);
php > echo $a->format(DateTime::ISO8601);
90090-08-24T00:00:00+0000

Loop over specific dates (Cross months) in PHP

I'm working on a project that produces reports on a weekly basis, so if today's date is "2013/09/05" the code has to figure out what was the date seven days ago, which is "2013/08/29", taking into account that some months are longer than others.
and then i want to run the dates against the database looking for matches ...
this is what i have done so far but its not working.
// Start date
$text = explode('/', $date); //2013/09/05
$day = $text[2];
$month = $text[1];
$year = $text[0];
$past_day = $day - 7; //-2
// determine if $past_day is negative
if ($past_day < 0){
$month = $month - 1; //08
$var = $day - 0; //2
$num = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$var = ($num - $var); // 29
$start_date = $year."/".$month."/".$var;
}else{
$start_date = $year."/".$month."/".$past_day;
}
Thanks alot guys!
try this :)
$date = "2013/09/05";
// Start date
$text = explode('/', $date); //2013/09/05
$day = $text[2];
$month = $text[1];
$year = $text[0];
$past_day = $day - 7; //-2
// determine if $past_day is negative
if ($past_day < 0){
$month = $month - 1; //08
$var = ($past_day)*-1; //2
$num = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$var = ($num - $var); // 29
$start_date = $year."/".$month."/".$var;
}else{
$start_date = $year."/".$month."/".$past_day;
}

Categories