views:

140

answers:

3

Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP?

Note: I am rewriting an existing system that is painfully slow.

+6  A: 

Use str_split():

$string = '0123456789012345';
$sets = str_split($string, 4);
print_r($sets);

The output:

Array
(
    [0] => 0123
    [1] => 4567
    [2] => 8901
    [3] => 2345
)

Then of course to insert hyphens between the sets you just implode() them together:

echo implode('-', $sets); // echoes '0123-4567-8901-2345'
yjerem
Assuming the OP wants the hyphens inserted, you'd probably then want to do implode( '-', $sets ).
Rob
Yeah, edited that in while you were commenting. At first I assumed he knew the implode() function.
yjerem
I do, I know how to do this also, I was A) hoping for something different I didn't already know about, b) putting it out there for other persons, since I've been asked about this 3 times today.
Unkwntech
What's the data source? If it's a DB, you can have the DB format it for you before it even gets to PHP.
DreamWerx
A: 

If you are looking for a more flexible approach (for e.g. phone numbers), try regular expressions:

preg_replace('/^(\d{4})(\d{4})(\d{4})(\d{4})$/', '\1-\2-\3-\4', '0123456789012345');

If you can't see, the first argument accepts four groups of four digits each. The second argument formats them, and the third argument is your input.

strager
I'm not sure if this wouldn't work better? preg_replace('/(\d{4})/', '-\1', '0123456789012345');
Loki
That wouldn't work, since you'd be left with a '-' hanging in the front of the output. It also kills some of the flexibility. I have edited my post to use the {4} syntax, though.
strager
A: 

This is a bit more general:

<?php

// arr[string] = strChunk(string, length [, length [...]] );
function strChunk() {
    $n = func_num_args();
    $str = func_get_arg(0);
    $ret = array();

    if ($n >= 2) {
     for($i=1, $offs=0; $i<$n; ++$i) {
      $chars = abs( func_get_arg($i) );
      $ret[] = substr($str, $offs, $chars);
      $offs += $chars;
     }
    }

    return $ret;
}

echo join('-', strChunk('0123456789012345', 4, 4, 4, 4) );

?>
Hugh Bothwell