Jump to content

regex {min, max} range


spaghettio05

Recommended Posts

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!

 

 

Link to comment
https://forums.phpfreaks.com/topic/237269-regex-min-max-range/
Share on other sites

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.

Link to comment
https://forums.phpfreaks.com/topic/237269-regex-min-max-range/#findComment-1219303
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.