insert dash into string
Moderator: General Moderators
- SmokyBarnable
- Forum Contributor
- Posts: 105
- Joined: Wed Nov 01, 2006 5:44 pm
insert dash into string
I have string that has 9 digits in it. I want to insert a dash after the 5th number. Is there a string function I can use to accomplish this?
Re: insert dash into string
Should be lots of ways to do that. As a regex fan I would have to show the regex way to do it 
Code: Select all
preg_replace('/([0-9]{5})/i', '$1-', '123456789');- SmokyBarnable
- Forum Contributor
- Posts: 105
- Joined: Wed Nov 01, 2006 5:44 pm
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
Re: insert dash into string
Code: Select all
<?php
$str = '932348787';
$str = substr($str, 0, 5) . '-' . substr($str, 5);
?>- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Re: insert dash into string
Code: Select all
$digits = implode('-', str_split($digits, 5));- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
Re: insert dash into string
Well then let's convolute this baby...
I like your better Jcart. 
Code: Select all
<?php
$new = '';
for ($i = 0; $i < strlen($str); $i++) {
$new .= $str[$i];
if ($i == 5) {
$new .= '-';
}
}
echo $new;
?>