PHP字符串拆分常规

问题描述 投票:0回答:1

常规exp =(数字)*(A | B | DF | XY)+(数字)+

我真的很困惑这种模式我想用PHP分隔此字符串,有人可以帮我我的输入可能是这样的

  1. A1234
  2. B 1239
  3. 1A123
  4. 12A123
  5. 1A 1234
  6. 12 A 123
  7. 1234 B 123456789
  8. 12 XY 1234567890

并转换为此

Array
(
    [0] => 12
    [1] => XY
    [2] => 1234567890
)

<?php
$input = "12    XY      123456789";
print_r(preg_split('/\d*[(A|B|DF|XY)+\d+]+/', $input, 3));
//print_r(preg_split('/[\s,]+/', $input, 3));
//print_r(preg_split('/\d*[\s,](A|B)+[\s,]\d+/', $input, 3));
php regex string split preg-split
1个回答
0
投票

您可以匹配并捕获数字,字母和数字:

$input = "12    XY      123456789";
if (preg_match('/^(?:(\d+)\s*)?(A|B|DF|XY)(?:\s*(\d+))?$/', $input, $matches)){
    array_shift($matches);
    print_r($matches);
}

请参见PHP demoregex demo

© www.soinside.com 2019 - 2024. All rights reserved.