簡體   English   中英

PHP 字符串拆分規則

[英]PHP string split regular

正則 exp = (位數)*(A|B|DF|XY)+(位數)+

我對這種模式感到困惑真的我想在 PHP 中分隔這個字符串,有人可以幫助我我的輸入可能是這樣的

  1. A1234
  2. B 1239
  3. 1A123
  4. 12A123
  5. 1A 1234
  6. 12 123
  7. 1234乙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));

您可以匹配並捕獲數字、字母和數字:

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

請參閱PHP 演示正則表達式演示

  • ^ - 字符串的開頭
  • (?:(\d+)\s*)? - 可選序列:
    • (\d+) - 第 1 組:任何或多個數字
    • \s* - 0+ 個空格
  • (A|B|DF|XY) - 第 2 組: ABDFXY
  • (?:\s*(\d+))? - 可選序列:
    • \s* - 0+ 個空格
    • (\d+) - 第 3 組:任何或多個數字
  • $ - 字符串結束。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM