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

In PHP, you can split a string containing mixed letters and numbers into separate arrays using preg_split() with regular expressions. This method allows you to extract numbers and letters independently.

Using preg_split() with Regular Expressions

The approach uses two different regular expression patterns − one to split by digits and extract letters, another to split by letters and extract digits ?

<?php
$values = "5j4o5h8n";

// Split by digits to get letters
$letters = preg_split("/\d+/", $values);
array_shift($letters); // Remove empty first element
print_r($letters);

// Split by letters to get numbers  
$numbers = preg_split("/[a-z]+/", $values);
array_pop($numbers); // Remove empty last element
print_r($numbers);
?>
Array
(
    [0] => j
    [1] => o
    [2] => h
    [3] => n
)
Array
(
    [0] => 5
    [1] => 4
    [2] => 5
    [3] => 8
)

Alternative Method Using preg_match_all()

For a more direct approach, you can use preg_match_all() to extract letters and numbers separately ?

<?php
$values = "5j4o5h8n";

// Extract all letters
preg_match_all('/[a-z]/', $values, $letterMatches);
$letters = $letterMatches[0];

// Extract all numbers
preg_match_all('/\d/', $values, $numberMatches);
$numbers = $numberMatches[0];

echo "Letters: ";
print_r($letters);
echo "Numbers: ";
print_r($numbers);
?>
Letters: Array
(
    [0] => j
    [1] => o
    [2] => h
    [3] => n
)
Numbers: Array
(
    [0] => 5
    [1] => 4
    [2] => 5
    [3] => 8
)

Comparison

Method Function Used Array Cleanup Required
Split Method preg_split() Yes (array_shift/pop)
Match Method preg_match_all() No

Conclusion

Both methods effectively separate letters and numbers from mixed strings. The preg_match_all() approach is cleaner as it directly extracts the desired characters without requiring array cleanup functions.

Updated on: 2026-03-15T09:36:02+05:30

618 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements