rojascorrine
rojascorrine

Reputation: 13

How to split a string into chunks of non-fixed lengths using php?

End goal: Changing chunks of numbers in a database like 0000000 and 22222 and 333333333333 into different lengths. For example, phone numbers that may include prefixes like country codes (e.g. +00 (000) 000-0000, or a pattern of 2, 3, 3, 4), so the option of being able to change the length depending on a different phone number format would be nice.

I love the idea of using explode or chunk_split for the simplicity, as I will be processing a lot of data and I don't want it to drain the server too much:

$string = "1111111111";     
$new_nums = chunk_split($string, 3, " ");
echo $new_nums;

^ Only problem here is that I can only use one digit for the length.

What's the best way to go about it? Should I create a function?

Upvotes: 1

Views: 540

Answers (2)

Crackertastic
Crackertastic

Reputation: 4913

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? 

Upvotes: 2

Petah
Petah

Reputation: 46060

With regex?

$regex = "/(\\d{2})(\\d{3})(\\d{3})(\\d{4})/"; 
$number = "111111111111"; 
$replacement = "+$1 ($2) $3-$4"; 

$result = preg_replace($regex, $replacement, $number);

https://regex101.com/r/gS1uC1/1

Upvotes: 2

Related Questions