Page 1 of 1

insert dash into string

Posted: Thu Apr 10, 2008 1:05 pm
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?

Re: insert dash into string

Posted: Thu Apr 10, 2008 1:08 pm
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');

Re: insert dash into string

Posted: Thu Apr 10, 2008 1:22 pm
by SmokyBarnable
:)

Re: insert dash into string

Posted: Thu Apr 10, 2008 3:40 pm
by RobertGonzalez

Code: Select all

<?php
$str = '932348787';
$str = substr($str, 0, 5) . '-' . substr($str, 5);
?>

Re: insert dash into string

Posted: Thu Apr 10, 2008 5:47 pm
by John Cartwright

Code: Select all

$digits = implode('-', str_split($digits, 5));
Code off ;)

Re: insert dash into string

Posted: Thu Apr 10, 2008 6:17 pm
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: