PHP split string into integer element and string

后端 未结 5 1866
小蘑菇
小蘑菇 2020-11-30 11:09

I have a string say: Order_num = \"0982asdlkj\"

How can I split that into the 2 variables, with the number element and then another variable with the le

相关标签:
5条回答
  • 2020-11-30 11:35

    Use preg_match() with a regular expression of (\d+)([a-zA-Z]+). If you want to limit the number of digits to 1-4 and letters to 6-9, change it to (\d+{1,4})([a-zA-Z]{6,9}).

    preg_match("/(\\d+)([a-zA-Z]+)/", "0982asdlkj", $matches);
    print("Integer component: " . $matches[1] . "\n");
    print("Letter component: " . $matches[2] . "\n");
    

    Outputs:

    Integer component: 0982
    Letter component: asdlkj
    

    http://ideone.com/SKtKs

    0 讨论(0)
  • 2020-11-30 11:35

    You can also do it using preg_split by splitting your input at the point which between the digits and the letters:

    list($num,$alpha) = preg_split('/(?<=\d)(?=[a-z]+)/i',$Order_num);
    

    See it

    0 讨论(0)
  • 2020-11-30 11:42

    You can use a regex for that.

    preg_match('/(\d{1,4})([a-z]+)/i', $str, $matches);
    array_shift($matches);
    list($num, $alpha) = $matches;
    
    0 讨论(0)
  • 2020-11-30 11:47

    Check this out

    <?php
    $Order_num = "0982asdlkj";
    $split=split("[0-9]",$Order_num);
    $alpha=$split[(sizeof($split))-1];
    $number=explode($alpha, $Order_num);
    echo "Alpha -".$alpha."<br>";
    echo "Number-".$number[0];
    ?>
    

    with regards

    wazzy

    0 讨论(0)
  • 2020-11-30 11:49

    You can use preg_split using lookahead and lookbehind:

    print_r(preg_split('#(?<=\d)(?=[a-z])#i', "0982asdlkj"));
    

    prints

    Array
    (
        [0] => 0982
        [1] => asdlkj
    )
    

    This only works if the letter part really only contains letters and no digits.

    Update:

    Just to clarify what is going on here:

    The regular expressions looks at every position and if a digit is before that position ((?<=\d)) and a letter after it ((?=[a-z])), then it matches and the string gets split at this position. The whole thing is case-insensitive (i).

    0 讨论(0)
提交回复
热议问题