【问题标题】:PHP string split regularPHP字符串拆分规则
【发布时间】:2020-09-09 07:00:21
【问题描述】:

正则表达式 = (位数)*(A|B|DF|XY)+(位数)+

我真的对这种模式感到困惑 我想在 PHP 中分隔这个字符串,有人可以帮助我 我的输入可能是这样的

  1. A1234
  2. B 1239
  3. 1A123
  4. 12A123
  5. 1A 1234
  6. 12 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】:

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

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

    请参阅PHP demo 和regex demo。

    • ^ - 字符串开头
    • (?:(\d+)\s*)? - 可选序列:
      • (\d+) - 第 1 组:任何或多个数字
      • \s* - 0+ 个空格
    • (A|B|DF|XY) - 第 2 组:A、B、DF 或 XY
    • (?:\s*(\d+))? - 可选序列:
      • \s* - 0+ 个空格
      • (\d+) - 第 3 组:任何或多个数字
    • $ - 字符串结束。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多