iKode iKode - 24 days ago 4
PHP Question

Regex to convert time format replace . with :

I need help with a regex, that I'm struggling with.

I'd like to convert:

9.15-11.15


to:

9:15-11:15


I have gotten as far as:

$message = preg_replace('/([0-9]{1,2}+)\.([0-9]{1,2}+)\-([0-9]{1,2}+)\.([0-9]{1,2}+)/', '$0:$1-$3:$4', $message);


This returns "9.15-11.15:9-11:15" though.

I'm not 100% sure if the issue is the match I'm making or my use of preg_replace?

Answer

If you do need a regex for that:

$message = 'Hello. This is some string with 9.15-11.15 time inside, and I don\'t want to replace the DOTS... inside';
$message = preg_replace('/(\d{1,2})\.(\d{1,2})\-(\d{1,2})\.(\d{1,2})/','$1:$2-$3:$4', $message);
var_dump($message);
// string(102) "Hello. This is some string with 9:15-11:15 time inside, and I don't want to replace the DOTS... inside"
Comments