I have the following date like this
20120809
I want to separate this with '-' and make this to
2012-08-09
using regex.
Is there is a simple solution to this using PHP? Anything will be fine.
You could just use date_parse_from_format
, the docs are here. In your case, that would make for:
date_parse_from_format('Ymd',$dateIn);
Gives an array back, so you can pretty much do as you please from there on end
As @Rocket said, you can also get the DateTime
object, which gives you all sorts of goodies, too. more docs to read ;)
Agreed with others that you don't need a regex to do this, but...
preg_replace('/(\d{4})(\d\d)(\d\d)/', '\1-\2-\3', $str);
With PHP though, you can use substr_replace
to insert dashes:
$str = substr_replace($str, '-', 4, 0);
$str = substr_replace($str, '-', 7, 0);
If you want to use a regex, it's simple. Just use \d
with a quantifier like {4}
.
preg_replace('/(\d{4})(\d{2})(\d{2})/', '$1-$2-$3', '20120809');
use date()
and strtotime()
?
date('Y-m-d',strtotime('20120809'));
Using regex for this thing is completely wrong and there are better ways to do that like substr() ...
But here is what you want:
<?php
$string = '20120809';
preg_match( '/(\d{4})(\d{2})(\d{2})/', $string, $parts);
unset($parts[0]);
$result = implode('-', $parts); //2012-08-09
?>