spaghettio05 Posted May 23, 2011 Share Posted May 23, 2011 I'm new to regex and having some difficulty. Here is some sample code: <?php $t = "Apple: blah blah blah 12 Mar 2003 http"; $pat = '/(Apple|Orange): (?P<extract>.+)(\d{1,2} \w{3} \d{4})? http/'; preg_match($pat, $t, $matches); print trim($matches["extract"]); ?> I have 2 questions: 1) I want it such that the day in the date can be either 1 or 2 digits, so I would like it to return "blah blah blah" instead of "blah blah blah 1". 2) I would also like the date to be optional (it may be there sometimes, not other times), but can't get it to work by adding a ? after the date grouping: $pat = '/(Apple|Orange:): (?P<extract>.+)(\d{1,2} \w{3} \d{4})? http/'; In this case it returns: "blah blah blah 12 Mar 2003" This seems simple but I can't figure it out. Help would be greatly appreciated! Quote Link to comment https://forums.phpfreaks.com/topic/237269-regex-min-max-range/ Share on other sites More sharing options...
btherl Posted May 23, 2011 Share Posted May 23, 2011 The problem is that ".+" will match anything, including the date string. If you make the date string optional, the ".+" will eat up the date string, because it knows it doesn't need the date string in order to match the expression. One possible solution is to use two regexp, one with a compulsory date and a second one with no date. First you try to match the full expression with compulsory date string. If that fails, then try matching without the date string. Quote Link to comment https://forums.phpfreaks.com/topic/237269-regex-min-max-range/#findComment-1219303 Share on other sites More sharing options...
requinix Posted May 24, 2011 Share Posted May 24, 2011 Stick a space in there. (?P.+) (\d{1,2} Quote Link to comment https://forums.phpfreaks.com/topic/237269-regex-min-max-range/#findComment-1219319 Share on other sites More sharing options...
JAY6390 Posted May 24, 2011 Share Posted May 24, 2011 Couldn't you just add ? after the .+ /(Apple|Orange): (?P<extract>.+?)(\d{1,2} \w{3} \d{4})? http/ so that it's not greedy Quote Link to comment https://forums.phpfreaks.com/topic/237269-regex-min-max-range/#findComment-1219508 Share on other sites More sharing options...
spaghettio05 Posted May 24, 2011 Author Share Posted May 24, 2011 Great, thanks for the responses - it worked! Quote Link to comment https://forums.phpfreaks.com/topic/237269-regex-min-max-range/#findComment-1219599 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.