Regex backreference issue

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I'm in the process of building a templating system, and one of the
numerous fields that can be used is in the format of }, as

} specifies today + 10 days,
} specifies today - 5 days.

Simple, right? So, I've got a regex that looks for '/{{date([+\-])(\d
)}}/' and replaces it with date ('Y-m-d', (strtotime (date ('Y-m-
d' . " days"))))

So, you would think given } this would output "2009-06-01".
Unfortunately, it returns the default 1969-12-31 (IOW the resulting
strtotime is 0). Plenty of debugging shows the backreferences are
returning the correct information. Using the more aesthetically
correct DateTime::modify class has the same result.

Rather than continuing to bang my head for several more hours, does
anyone have suggestions? I'm sure there's something really simple I'm

Re: Regex backreference issue

On 31 May 2009, wrote:

Quoted text here. Click to load it


I assume there's no whitespace after "\d" in your source code.  
Using the /x modifier would help when posting regex patterns on

Since you don't escape the initial "{{" and end "}}" characters, it
has some potential problems should future changes need to be made.  
These have special meaning in PCRE regex, as demonstrated in your
own pattern, even.

Just a nitpick, but the "-" in your character class need not be
escaped when it is the last character in the character class.  
Again, using the /x modifier to allow whitespace and easy use of
comments is almost always a good idea:

$pattern = '/\{\{ date ([+-]) (\d) \}\}/x';

Quoted text here. Click to load it

You should do some more reading in the manual for the date() and
strtotime() functions, as your strtotime() call is very strange.  
You'll probably want to use preg_replace_callback() in this case.  
Here's the callback I'd use:

function daysOffset($matches) {
  return date(
    strtotime($matches[1] . $matches[2] . ' days')

Using preg_replace_callback():


$email = str_replace('sig.invalid', '', $from);

Anonymous (1984 IOCCC winner):
int i;main()"];read('-'-'-',i+++"hell\
o, world!\n",'/'/'/'));}read(j,i,p)

Site Timeline