Skip to content
Advertisement

How do I split the letters and numbers to 2 arrays from a string in PHP

I would like to know how to split both letters and numbers in 2 separate arrays, for example if I have $string = "2w5d15h9s";, then I want it to become

$letters = ["w", "d", "h", "s"];

$numbers = [2, 5, 15, 9];

Anybody got any idea of how to do it?

I’m basically trying to make a ban command and I want to make it so you can specify a time for the ban to expire.

Advertisement

Answer

Use preg_split:

$string = "2w5d15h9s";
$letters = preg_split("/d+/", $string);
array_shift($letters);
print_r($letters);
$numbers = preg_split("/[a-z]+/", $string);
array_pop($numbers);
print_r($numbers);

This prints:

Array
(
    [0] => w
    [1] => d
    [2] => h
    [3] => s
)

Array
(
    [0] => 2
    [1] => 5
    [2] => 15
    [3] => 9
)

Note that I am using array_shift or array_pop above to remove empty array elements which arise from the regex split. These empty entries occur because, for example, when spitting on digits the first character is a digit, which leaves behind an empty array element to the left of the first actual letter.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement