insert dash into string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
SmokyBarnable
Forum Contributor
Posts: 105
Joined: Wed Nov 01, 2006 5:44 pm

insert dash into string

Post by SmokyBarnable »

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?
aCa
Forum Newbie
Posts: 11
Joined: Sun Apr 06, 2008 3:43 pm

Re: insert dash into string

Post by aCa »

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');
User avatar
SmokyBarnable
Forum Contributor
Posts: 105
Joined: Wed Nov 01, 2006 5:44 pm

Re: insert dash into string

Post by SmokyBarnable »

:)
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: insert dash into string

Post by RobertGonzalez »

Code: Select all

<?php
$str = '932348787';
$str = substr($str, 0, 5) . '-' . substr($str, 5);
?>
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: insert dash into string

Post by John Cartwright »

Code: Select all

$digits = implode('-', str_split($digits, 5));
Code off ;)
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: insert dash into string

Post by RobertGonzalez »

Well then let's convolute this baby...

Code: Select all

<?php
$new = '';
for ($i = 0; $i < strlen($str); $i++) {
    $new .= $str[$i];
    if ($i == 5) {
        $new .= '-';
    }
}
 
echo $new;
?>
I like your better Jcart. :wink:
Post Reply