PHP 使用 preg_match 获取匹配的订单 ID

PHP get matched order id using preg_match

我正在编写一个 PHP 代码,需要从文本中获取一些订单 ID,订单 ID 格式如下

  Ex- 
          201812321910AT
          201812321810AT        
          201812321910AT-001
          201812321910AT-001

里面的文字如下

      lorem ispmes dolter yexy tesy 201812321910AT l tesyui lorem ispmes 
dolter gjexy tesy    201812321810AT hekfl lorem tesxts
 201812321910AT-001 lot kyesu oerd 201812321910AT-001 lfs tes ol sghn

我试过这个代码,但它也 returns 一些其他匹配的单词有 12-15 个字母

preg_match('/\b[A-Z]{12,15}\b/', $string, $matches);
var_dump($matches);

我对 php preg_match 模式没有深入的了解,有人可以帮助我使用 PHP 获得匹配的订单 ID。 以上订单编号仅为示例通常订单编号有 12 个数字然后是 AT 字母,并且一些订单有 12 个数字 AT 然后是 3 个数字后跟 -.

此正则表达式应该足以捕获您 post、

中的那些订单 ID
\b\d{12}[A-Z]{2}(?:-\d{3}\b)?

Demo

不需要让它比它更复杂。
捕获 12 位数字然后偷懒直到 space.

preg_match_all("/(\d{12}AT.*?)\s/", $str, $matches);
var_dump($matches);

输出:

array(2) {
  [0]=>
  array(4) {
    [0]=>
    string(15) "201812321910AT "
    [1]=>
    string(15) "201812321810AT "
    [2]=>
    string(19) "201812321910AT-001 "
    [3]=>
    string(19) "201812321910AT-001 "
  }
  [1]=>
  array(4) {
    [0]=>
    string(14) "201812321910AT"
    [1]=>
    string(14) "201812321810AT"
    [2]=>
    string(18) "201812321910AT-001"
    [3]=>
    string(18) "201812321910AT-001"
  }
}

https://3v4l.org/S4CSr