【问题标题】:Need the exact pattern of preg_match to extract values in PHP需要 preg_match 的确切模式来提取 PHP 中的值
【发布时间】:2017-06-15 14:35:11
【问题描述】:

我有一个用;#<number>;# 分隔的字符串:

aaaa;#112;#bbbb;#113;#cccc;#112;#dddd

我想使用preg_match() 在数组中查找所有aaaabbbb 等。

正则表达式模式应该是什么?

到目前为止我一直在尝试什么:

preg_match('/\;\#(?:[0-9]+)?/', $franchCont, $matches);

【问题讨论】:

  • match?为什么不splitpreg_split('/;#\d+;#/', $string)
  • @falsetru,是的,它有效,再次感谢 :)
  • 我正在尝试:preg_match('/\;\#(?:[0-9]+)?/', $franchCont, $matches);,但 @falsetru 建议的 preg_split为我工作
  • @aniruddha 不要编辑问题以包含答案。答案在页面下方,你应该把它移到那里,或者让 falsetru 把它作为答案发布。

标签: php arrays regex preg-match


【解决方案1】:

您正在尝试按分隔符进行拆分;所以preg_split是更合适的函数:

$parts = preg_split('/;#\d+;#/', $string);

【讨论】:

    【解决方案2】:

    您可以使用拆分或匹配。

    既然你问了匹配,一种方法是

    https://regex101.com/r/P5MPDf/1

    (?:;#\d+;#(*SKIP)(*FAIL)|(?:(?!;#\d+;#).)+)

    解释

     (?:
          ;\# \d+ ;\# (*SKIP) (*FAIL)   # Consume, but fail the delimiter
       |                              # or,
          (?:                           # Get all up until the delimiter
               (?! ;\# \d+ ;\# )
               . 
          )+
     )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多