How to separate letters and digits from a string in php



PHP Snippet 1:

$numbers = preg_replace('/[^0-9]/', '', $str);
$letters = preg_replace('/[^a-zA-Z]/', '', $str);

PHP Snippet 2:

$arr = preg_split('/(?<=[0-9])(?=[a-z]+)/i',$str);

PHP Snippet 3:

<?php
$str = '12jan';
$arr = preg_split('/(?<=[0-9])(?=[a-z]+)/i',$str);                                                               
print_r($arr);

PHP Snippet 4:

Array
(
    [0] => 12
    [1] => jan
)

PHP Snippet 5:

preg_match_all('/^(\d+)(\w+)$/', $str, $matches);

var_dump($matches);

$day = $matches[1][0];
$month = $matches[2][0];

PHP Snippet 6:

preg_match_all('/(\d)|(\w)/', $str, $matches);

$numbers = implode($matches[1]);
$letters = implode($matches[2]);

var_dump($numbers, $letters);

PHP Snippet 7:

$string = "12312313sdfsdf24234";
preg_match_all('/([0-9]+|[a-zA-Z]+)/',$string,$matches);
print_r($matches);

PHP Snippet 8:

function stringSeperator($string,$type_return){

    $numbers =array();
    $alpha = array();
    $array = str_split($string);
    for($x = 0; $x< count($array); $x++){
        if(is_numeric($array[$x]))
            array_push($numbers,$array[$x]);
        else
            array_push($alpha,$array[$x]);
    }// end for         

    $alpha = implode($alpha);
    $numbers = implode($numbers);

    if($type_return == 'number')    
    return $numbers;
    elseif($type_return == 'alpha')
    return $alpha;

}// end function

PHP Snippet 9:

preg_split(
    '~(?:\d+|\D+)\K~',
    $string,
    0,
    PREG_SPLIT_NO_EMPTY
)

PHP Snippet 10:

preg_split(
    '~(\d+)~',
    $string,
    0,
    PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE 
)

PHP Snippet 11:

var_export(sscanf('12jan', '%d%s'));

PHP Snippet 12:

array (
  0 => 12,
  1 => 'jan',
)

PHP Snippet 13:

$string="12jan";
$chars = '';
$nums = '';
for ($index=0;$index<strlen($string);$index++) {
    if(isNumber($string[$index]))
        $nums .= $string[$index];
    else    
        $chars .= $string[$index];
}
echo "Chars: -$chars-<br>Nums: -$nums-";


function isNumber($c) {
    return preg_match('/[0-9]/', $c);
}