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


For this, use preg_split() along with array_shift() and array_pop(). Let’s say the following is our string with letters and numbers 

$values = "5j4o5h8n";

We want to display the numbers and letters in separate arrays.

Example

The PHP code is as follows

 Live Demo

<!DOCTYPE html>
<html>
<body>
<?php
$values = "5j4o5h8n";
$singleValues = preg_split("/\d+/", $values);
array_shift($singleValues);
print_r($singleValues);
$resultNumber= preg_split("/[a-z]+/", $values);
array_pop($resultNumber);
print_r($resultNumber);
?>
</body>
</html>

Output

This will produce the following output

Array ( [0] => j [1] => o [2] => h [3] => n ) Array ( [0] => 5 [1] => 4 [2] => 5 [3] => 8 )

Updated on: 13-Oct-2020

375 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements