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? Link to comment https://forums.phpfreaks.com/topic/92128-string-manipulation-problem/ 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> Link to comment https://forums.phpfreaks.com/topic/92128-string-manipulation-problem/#findComment-471817 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. Link to comment https://forums.phpfreaks.com/topic/92128-string-manipulation-problem/#findComment-471847 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? Link to comment https://forums.phpfreaks.com/topic/92128-string-manipulation-problem/#findComment-471883 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. Link to comment https://forums.phpfreaks.com/topic/92128-string-manipulation-problem/#findComment-471944 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? Link to comment https://forums.phpfreaks.com/topic/92128-string-manipulation-problem/#findComment-471961 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.