Regex Optional Groups?

后端 未结 3 1191
面向向阳花
面向向阳花 2021-01-04 02:01

I seem to have confused myself with a preg_match regex I\'m doing, so fresh eyes and help would be appreciated.

My current regex is as follows:

/<         


        
相关标签:
3条回答
  • 2021-01-04 02:02

    Like this:

    /<!--menu:start(?::\((\d),(\d)\))?-->(.*?)<!--menu:end-->/se
    

    I've added a non-capturing group, (?: ), around the part you want to be optional, and then suffixed it with a question mark: (?:<optional content>)?

    0 讨论(0)
  • 2021-01-04 02:05

    This uses an optional non-capturing group -- (?: )? -- to match your optional part, and also \d instead of [0-9] to match digits:

    /<!--menu:start(?::\((\d),(\d)\))?-->(.*?)<!--menu:end-->/se
    

    If numbers in parentheses can consist of more than one digit, use this one instead:

    /<!--menu:start(?::\((\d+),(\d+)\))?-->(.*?)<!--menu:end-->/se
    
    0 讨论(0)
  • 2021-01-04 02:10

    Enclose with a non matching group and set it to optional : (?:...)?

    /<!--menu:start(?::\(([0-9])\,([0-9])\))?-->(.*?)<!--menu:end-->/se
    
    0 讨论(0)
提交回复
热议问题