使用preg_match从完整的发送中提取一些信息

时间:2018-03-12 07:09:19

标签: preg-match preg-match-all

我想在php中使用preg_match提取特定信息。有什么想法吗?

sample text = 2xMUA Matte Lipstick - Totally Nude[300]=[600]

我想

product_name = MUA Matte Lipstick - Totally Nude
product_qty = 2
product_price = 300
product_subtotal = 600

1 个答案:

答案 0 :(得分:1)

您可以在(命名)captured groups中捕获您的值。

试试这样:

(?<qty>\d+)x(?<name>[^[]+)\[(?<price>[^]]+)\]=\[(?<subtotal>[^]]+)\]

那将匹配:

(?<qty>      # Named captured group qty
  \d+        # One or more digits
)            # Close group
x            # Match x
(?<name>     # Named captured group name
  [^[]+      # Match not [ one or more times
)            # Close group
\[           # Match [
(?<price>    # Named captured group price
  [^]]+      # Match not ] one or more times
)            # Close group
\]=\[        # Match ]=[
(?<subtotal> # Named captured group subtotal
  [^]]+      # # Match not ] one or more times
)            # Close group
\]           # Match ]

Demo php

或者没有命名的捕获组:

(\d+)x([^[]+)\[([^]]+)\]=\[([^]]+)\]