karldesign Posted April 12, 2007 Share Posted April 12, 2007 I have a string (phone number) that I wish to add spaces to at set intervals of 4 and 3. Is this achievable and would it be Regex or Explode? If so, how? (ie: 00001234567 becomes 0000 123 4567) Link to comment https://forums.phpfreaks.com/topic/46711-solved-explode-or-regex/ Share on other sites More sharing options...
obsidian Posted April 12, 2007 Share Posted April 12, 2007 I believe in a case like this, you'll be fastest in processing to use substr() since you already know the intervals: <?php $num = '00001234567'; $new = substr($num, 0, 4) . ' ' . substr($num, 4, 3) . ' ' . substr($num, 7); echo $new; ?> Link to comment https://forums.phpfreaks.com/topic/46711-solved-explode-or-regex/#findComment-227552 Share on other sites More sharing options...
karldesign Posted April 12, 2007 Author Share Posted April 12, 2007 That is what I had, just thought there may have been a better way! Cheers very much. Link to comment https://forums.phpfreaks.com/topic/46711-solved-explode-or-regex/#findComment-227558 Share on other sites More sharing options...
Lumio Posted April 12, 2007 Share Posted April 12, 2007 I don't know a way with explode, but with Regex and also with substr, it's a good way. You can do the same with Regex like that: <?php $num = '00001234567'; preg_match('{([\d]{4})([\d]{3})([\d]{4})}', $num, $match); $new = $match[1].' '.$match[2].' '.$match[3]; echo $new; ?> Link to comment https://forums.phpfreaks.com/topic/46711-solved-explode-or-regex/#findComment-227562 Share on other sites More sharing options...
effigy Posted April 12, 2007 Share Posted April 12, 2007 TMTOWTDI: <?php $num = '00001234567'; echo preg_replace('/(?<=^\d{4})|(?=\d{4}\z)/', ' ', $num); ?> Link to comment https://forums.phpfreaks.com/topic/46711-solved-explode-or-regex/#findComment-227681 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.