D
D
danforth2017-10-09 15:51:15
Regular Expressions
danforth, 2017-10-09 15:51:15

How to make a regular expression with remember but exclude part?

Hello!
https://regex101.com/r/FnawtN/1
In short, there are line options that indicate days, hours, and minutes (duration):

Day 5 1:23
pm 5:44 pm
12 pm 5:00 pm

At the output (for the 1st option) I want to get an array with values:
[
    'days' => 5,
    'hours' => 1,
    'minutes' => 23,
]

For each group to be named if minutes are not specified - let there be no such key in the array.
Is it possible to make sure that there are no empty values ​​in the array? If you open the link at the very beginning of the question, you can see that there are many empty Full Match.
Note that both "day hour" and "hour minute" can be given as input, and possibly even "day minute" if the hour is zero.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Dart, 2017-10-09
@gobananas

Is it possible to make sure that there are no empty values ​​in the array?

You can, but you probably have to check each value separately with regular expressions
https://regex101.com/r/qFflgP/1
[0-9]+[\s]{0,}д
[0-9]+[\s]{0,}ч
[0-9]+[\s]{0,}м

If any of the regular expressions did not work or returned an empty value, then manually set 0
if(!preg_match('/[0-9]+[\s]{0,}д/ismu', $string)){
   $days= 0;
}

And at the end do:
[
    'days' => $days,
    'hours' => $hours,
    'minutes' => $minutes,
]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question