How to separate letters and digits from a string in php

后端 未结 8 2010
攒了一身酷
攒了一身酷 2020-11-29 09: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 ge

相关标签:
8条回答
  • 2020-11-29 09:50
    <?php
    $data = "#c1";
    $fin =  ltrim($data,'#c');
    echo $fin;
    ?>
    
    0 讨论(0)
  • 2020-11-29 10:07
    preg_match_all('/^(\d+)(\w+)$/', $str, $matches);
    
    var_dump($matches);
    
    $day = $matches[1][0];
    $month = $matches[2][0];
    

    Of course, this only works when your strings are exactly as described "abc123" (with no whitespace appended or prepended).

    If you want to get all numbers and characters, you can do it with one regex.

    preg_match_all('/(\d)|(\w)/', $str, $matches);
    
    $numbers = implode($matches[1]);
    $letters = implode($matches[2]);
    
    var_dump($numbers, $letters);
    

    See it!

    0 讨论(0)
  • 2020-11-29 10:07

    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
    
    0 讨论(0)
  • 2020-11-29 10:08

    You can make use of preg_split to split your string at the point which is preceded by digit and is followed by letters as:

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

    Code in Action

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

    Result:

    Array
    (
        [0] => 12
        [1] => jan
    )
    
    0 讨论(0)
  • 2020-11-29 10:11
    $numbers = preg_replace('/[^0-9]/', '', $str);
    $letters = preg_replace('/[^a-zA-Z]/', '', $str);
    
    0 讨论(0)
  • 2020-11-29 10:12

    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);
    } 
    
    0 讨论(0)
提交回复
热议问题