How to separate letters and digits from a string i

2019-01-07 21:37发布

I have a string which is combination of letters and digits. For my application i have to separate a string with letters and digits: ex:If my string is "12jan" i hav to get "12" "jan" separately..

8条回答
欢心
2楼-- · 2019-01-07 22:01

Try This :

$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);
} 
查看更多
forever°为你锁心
3楼-- · 2019-01-07 22:02
$numbers = preg_replace('/[^0-9]/', '', $str);
$letters = preg_replace('/[^a-zA-Z]/', '', $str);
查看更多
beautiful°
4楼-- · 2019-01-07 22:03
<?php
$data = "#c1";
$fin =  ltrim($data,'#c');
echo $fin;
?>
查看更多
【Aperson】
5楼-- · 2019-01-07 22:05

This works for me as per my requirement, you can edit as per yours

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
查看更多
SAY GOODBYE
6楼-- · 2019-01-07 22:05

Having worked more with PHPExcel, such operations are common. #Tapase,. Here is a preg_split that gets you want you want with space within the string.

<?php
$str = "12 January";
$tempContents = preg_split("/[\s]+/", $str);
foreach($tempContents as $temp){
echo '<br/>'.$temp;
}
?>

You can add a comma next to the s for comma seperated. Hope it helps someone. Anton K.

查看更多
再贱就再见
7楼-- · 2019-01-07 22:13
$string = "12312313sdfsdf24234";
preg_match_all('/([0-9]+|[a-zA-Z]+)/',$string,$matches);
print_r($matches);

this might work alot better

查看更多
登录 后发表回答