denhamd2 Posted February 20, 2008 Share Posted February 20, 2008 Hi, I have a date stored in variable $date in the format 12032008 I'm looking to create a new variable $datereformatted in the format 20080312,, would anyone know how to do this in PHP? Quote Link to comment Share on other sites More sharing options...
effigy Posted February 20, 2008 Share Posted February 20, 2008 <pre> <?php $str = '12032008'; echo preg_replace('/\A(\d{2})(\d{2})(\d{4})\z/', '$3$2$1', $str); ?> </pre> Quote Link to comment Share on other sites More sharing options...
dave420 Posted February 20, 2008 Share Posted February 20, 2008 <?php $str = '12032008'; echo substr($str, 4, 4).substr($str, 2, 2).substr($str, 0, 2); ?> Is significantly faster than using regular expressions. Quote Link to comment Share on other sites More sharing options...
effigy Posted February 20, 2008 Share Posted February 20, 2008 Is significantly faster than using regular expressions. One substr is, but what about multiple? And against an exact expression? Quote Link to comment Share on other sites More sharing options...
dave420 Posted February 20, 2008 Share Posted February 20, 2008 Well, it's not an exact expression - it still has to be matched against the string, bits of it captured, and then reconstituted in its final form. I ran it through xdebug, and the preg_replace took up most of the time every single time I ran a test. Regular expressions have quite an overhead compared to simply moving three bits of a string around using substr. Quote Link to comment Share on other sites More sharing options...
effigy Posted February 20, 2008 Share Posted February 20, 2008 It's exact in the sense that there is no flexibility in the pattern; therefore, the engine doesn't juggle characters around trying to match: the first mismatch is an immediate failure. Can you post some hard comparison numbers? I'm curious because I know that, yes, you wouldn't use a regexp to replace one character when you can use str_replace, but beyond that what do the numbers reflect? Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.