Reputation: 59
I have a string like this G5510ZCU1AQG2
.
the QG
last letters represent a date formatted like this 2017-07
.
the letter q
represent the year . and g
the month.
you keep count the letters to get the number.
I want to get the date from these letters .
I tried to make switch
statement but its not helpful and there is a lot of code to write.
is there simpler way to get the date as 2017-07
from this string G5510ZCU1AQG2
?
I'm sorry i'm still learning and i can't think of something useful
Upvotes: 0
Views: 59
Reputation: 3527
Here's how you can do that:
$str = "G5510ZCU1AQG2";
$year_letter = substr($str, -3, 1);
$month_letter = substr($str, -2, 1);
$year = 2000 + (ord($year_letter) - ord('A') + 1);
$month = ord($month_letter) - ord('A') + 1;
$date = sprintf("%02d-%d", $month, $year);
substr
.
Passing -3 and 1 means "get me 1 letter which is located 3 away from
the end". ord()
. Comparing it to the ASCII code of the first letter A gives us the number of the letter in the alphabet (+1 because it starts with 1, not with 0)$month . "-" . $year
. However, this would give us 7-2017 and we want a leading zero. That's what the sprintf
function is used for: "%02d-%d
means "print a 2-digit number with a leading zero, then a minus sign, then a digit."07-2017"
Cheers.
Upvotes: 1