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

PHPServer Side ProgrammingProgramming

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 )
raja
Published on 13-Oct-2020 08:06:20
Advertisements