简体   繁体   English

将字符和数字之间的字符串拆分为数组 PHP

[英]Split String between character and number into an array PHP

I have a string that looks like this:我有一个看起来像这样的字符串:

$data1 = "W97";
$data2 = "RP100";
$data3 = "MAL89";
$data4 = "UNIQ95";

The string will contain a char first then it will contain a number, i want to split the between the character and number into array, for example:该字符串将首先包含一个字符,然后它将包含一个数字,我想将字符和数字之间的值拆分为数组,例如:

print_r($this->splitString($data1)); //array([0]=>'W',[1]=>97)
print_r($this->splitString($data2)); //array([0]=>'RP',[1]=>100)
print_r($this->splitString($data3)); //array([0]=>'MAL',[1]=>89)
print_r($this->splitString($data4)); //array([0]=>'UNIQ',[1]=>95)

function splitString($string){
  $result = array();
  //???
  return $result;
}

How can i do this?我怎样才能做到这一点?

Assuming there is only ever one 'character' part, followed by one number part, this regexp will match them both separately:假设只有一个“字符”部分,后跟一个数字部分,这个正则表达式将分别匹配它们:

/^([A-Z]+)([0-9]+)$/

Used in preg_match() , this gives the following result:preg_match()中使用,这给出了以下结果:

$regexp = '/^([A-Z]+)([0-9]+)$/';
$string = 'ABC1234';
$matches = [];

preg_match($regexp, $string, $matches);

var_dump($matches);

// Output:
array(3) {
  [0] =>
  string(7) "ABC1234"
  [1] =>
  string(3) "ABC"
  [2] =>
  string(4) "1234"
}

Just unset (or ignore) the first index, and you're good to go.只需取消设置(或忽略)第一个索引,您就可以使用 go。

use this method this will work for you.使用这种方法,这对你有用。

$data1      = "W2020";
$data2      = "AB2020";
$data3      = "ZXCV2020";

print_r(splitString($data3));

function splitString($string){
    $alpha_string = '';
    $num_string = '';
    $array2 = str_split( $string );

    foreach($array2 as $value){
        if(is_numeric($value))
            $num_string .= $value;
         else
            $alpha_string .= $value;
    }
    $data_array = array($alpha_string, $num_string);

    return $data_array;
}

that's it.而已。 This will work.这将起作用。

Use lookaround:使用环视:

$data1 = "W97";
$data2 = "RP100";
$data3 = "MAL89";
$data4 = "UNIQ95";


print_r(splitString($data1)); //array([0]=>'W',[1]=>97)
print_r(splitString($data2)); //array([0]=>'RP',[1]=>100)
print_r(splitString($data3)); //array([0]=>'MAL',[1]=>89)
print_r(splitString($data4)); //array([0]=>'UNIQ',[1]=>95)

function splitString($string){
  $result = array();
  $result = preg_split('/(?<=[A-Z])(?=\d)/', $string);
  return $result;
}

Output: Output:

Array
(
    [0] => W
    [1] => 97
)
Array
(
    [0] => RP
    [1] => 100
)
Array
(
    [0] => MAL
    [1] => 89
)
Array
(
    [0] => UNIQ
    [1] => 95
)

Explanation:解释:

(?<=[A-Z])      # positive lookbehind, make sure we have a capital letter before the current position
(?=\d)          # positive lookahead, make sure we have a digit after the current position

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM