Although you mention a phone number in your example it sounds like you wanted something that could do more while also being allowed to specify multiple and variable chunk lengths. One way to do this is to create a function that takes your data, delimiter/separator character and a number of chunk values.
You could make use of func_num_args() and func_get_args() to figure out your chunk lengths.
Here is an example of such a function:
<?php
function chunkData($data, $separator)
{
$rebuilt = "";
$num = func_num_args();
$args = func_get_args();
if($num > 2)
{
for($i = 2; $i < $num; $i++)
{
if(strlen($data) > 0)
{
$string = substr($data, 0, $args[$i]);
$segment = strpos($data, $string);
if($segment !== false)
{
$rebuilt .= $string . $separator;
$data = substr_replace($data, "", 0, $args[$i]);
}
}
}
}
$rebuilt .= $data;
$rebuilt = rtrim($rebuilt, $separator);
return $rebuilt;
}
//Usage examples:
printf("Phone number: %s \n", chunkData("2835552093", "-", 3, 3, 4));
printf("Groups of three letters: %s \n", chunkData("ABCDEFGHI", " ", 3, 3, 3));
printf("King Roland's passcode: %s \n", chunkData("12345", ",", 1, 1, 1, 1, 1));
printf("Append leftovers: %s \n", chunkData("BlahBlahBlahJustPlainBlah", " ", 4, 4, 4));
printf("Doesn't do much: %s \n", chunkData("huh?", "-"));
?>
//Output:
Phone number: 283-555-2093
Groups of three letters: ABC DEF GHI
King Roland's passcode: 1,2,3,4,5
Append leftovers: Blah Blah Blah JustPlainBlah
Doesn't do much: huh?