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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.