duanjiao6731
2015-11-25 17:19
浏览 322
已采纳

从字符串中分离字母和数字

$str = 'ABC300';

How I can get values like

$alphabets = "ABC";
$numbers = 333;

图片转代码服务由CSDN问答提供 功能建议

  $ str ='ABC300'; 
   
 
  

我如何获得像

  $ alphabets =“ABC”; 
 $ numbers = 333; 
   
 <  / DIV>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dsgni26260 2015-11-25 17:29
    已采纳

    I have a idea , first remove numbers from the string and save in a variable. then remove alphabets from the $str variable and save. try the code

     $str = 'ABC300';
    $alf= trim(str_replace(range(0,9),'',$str));//removes number from the string 
    $number = preg_replace('/[A-Za-z]+/', '', $str);// removes alphabets from the string 
    echo $alf,$number;// your expected output 
    
    点赞 评论
  • douzao5487 2015-11-25 17:35

    A way to do that is to find all digits and use the array to replace original string with the digits inside.

    For example

    function extractDigits($string){
        preg_match_all('/([\d]+)/', $string, $match);
    
        return $match[0];
    }
    
    $str = 'abcd1234ab12';
    $digitsArray = extractDigits($str);
    $allAlphas = str_replace($digitsArray,'',$str);
    $allDigits = '';
    foreach($digitsArray as $digit){
       $allDigits .= $digit;
    }
    
    点赞 评论
  • douxin2002 2015-11-25 17:37

    Try something like this (it's not that fast)...

    $string = "ABCDE3883475";
    $numbers = "";
    $alphabets = "";
    $strlen = strlen($string);
    for($i = 0; $i <= $strlen; $i++) {
        $char = substr($string, $i, 1);
        if(is_numeric($char)) {
            $numbers .= $char;
        } else {
            $alphabets .= $char;
        }
    }
    

    Then all numbers should be in $numbers and all alphabetical characters should be in $alphabets ;)

    https://3v4l.org/Xh4FR

    点赞 评论

相关推荐 更多相似问题