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) Quote Link to comment 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; ?> Quote Link to comment 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. Quote Link to comment 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; ?> Quote Link to comment 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); ?> 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.