views:

1021

answers:

3

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:

/<!--menu:start:\(([0-9])\,([0-9])\)-->(.*?)<!--menu:end-->/se

I am looking to make the number input and colon e.g. :(1,4) optional, so it would match:

<!--menu:start--><!--menu:end-->

or

<!--menu:start:(0,3)--><!--menu:end-->
+5  A: 

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>)?

Blixt
Haha, that's a close tie... :)
subtenante
Indeed, it is =)
Blixt
Thanks guys :) Had to choose one!
Joel
+6  A: 

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

/<!--menu:start(?::\(([0-9])\,([0-9])\))?-->(.*?)<!--menu:end-->/se
subtenante
+1  A: 

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
Helen
Is there any advantage to using \d instead of [0-9]?
Joel
None actually, except that \d is shorter. :-)
Helen