Most efficient way to differentiate a key

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

Note. I am rewriting an existing system which is very slow.

0


source to share


3 answers


Use str_split () :

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

      

Output:



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

      

Then, of course, to insert a hyphen between sets, you simply implode () together:

echo implode('-', $sets); // echoes '0123-4567-8901-2345'

      

+6


source


If you're looking for a more flexible approach (like phone numbers) try regular expressions:

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

      



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

0


source


This is a little 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) );

?>

      

0


source







All Articles