Regex video mode duration string

I want to find all video length links in comments and convert them to anchor tags.

The duration might look like this:

01:20:55 (h:m:s)
20:30 (m:s)
1:21 (m:s)
1:35:12 (h:m:s)

      

I feel like I might be around, but I'm pretty new to regex

http://regexr.com/3bfmu

^([\d]{1,2}\:)?([\d]{1,2})?\:([\d]{1,2})$

      

to be used in this context:

$parsedTimeCommentString = preg_replace("/^([\d]{1,2}\:)?([\d]{1,2})?\:([\d]{1,2})$/", 
"<a href=\"#\" class=\"video-seek\" data-seek=\"$1:$2:$3\">$1:$2:$3</a>",
 $comment['comment']);

      

+3


source to share


3 answers


Remove the bindings and use a non-capturing group to disallow colons:

(?:(\d{1,2}):)?(\d{1,2}):(\d{2})

      



Live Demo

+3


source


It may sound strange, but I think it should look something like this:

(?<![\d:])(?:(?:(\d\d?):([0-5]\d))|([0-5]?\d)):([0-5]\d)(?![\d:])

      

keep the format: hh: mm: ss, h: mm: ss, mm: ss, m: ss and avoid matching incorrect (for time formatting) strings, for example: 1: 3: 4, 14: 1:14, 45: 4 : 4, 88:99, 345: 456 (like 45:45), 2: 3, etc.



DEMO

It fixes hours at $ 1 and seconds at $ 4, but minutes are fixed at $ 2 or $ 3.

0


source


I would reset the line bindings (^ $) so that your line matches timestamps in other text. Also, you have to make the second capture group non-optional, so something like ": 3" can't get through. And you will want to make it global with / g so that it replaces all occurrences. Something like that:

/([\d]{1,2}\:)?([\d]{1,2})\:([\d]{1,2})/g

      

0


source







All Articles