I am trying to minus or subtract by 1 the academic year of school year with this format, e.g. "2020-2021"
If it is 2020-2021
, I would like to change it 2019-2020
. Is there a way to solve this concern?
I considered trying to subtract using a hyphenated expression, but I am pretty stuck.
echo "2020-2021"-"1-1";
echo "Result: 2019-2020";
2
Answers
You can use explode and parse the value to subtract the value
You don’t need to complicate your task by trying to shoehorn
1-1
into your approach. Usepreg_replace_callback()
to target and decrement numeric substrings in one line of code.This approach targets the numbers and therefore will not break if your delimiting character(s) change.
Code: (Demo)
Decrementing the fullstring match
--$m[0]
could also be written as simple subtraction:$m[0] - 1
.