I have the following code that selects all the different template files out of a folder... The file names I have are:





I only want to select the ones without the _load in the file name so I used this code:

preg_match('/^template_(.*)[^[_load]]{0}\.php$/i', $layout_file, $layout_name)

The code works fine except it cuts the last character off the result... Instead of returning default or sub when I echo $layout_name[1], it shows defaul and su...

Any ideas what is wrong with my code?

+2  A: 

This part is totally up the creek:


This is the regex you want:

too much php

You'll have to use negative assertions. (read below why not)

preg_match('/^template_(.*?)(?!_load)\.php$/i', $layout_file, $layout_name)

Edit: come to think of it, that regexp won't actually work because "_load" will be consumed by the .*? part. My advice: don't use preg_match() to capture the name, use it to skip those that end with _load, e.g.

foreach (glob('template_*') as $filepath)
    if (preg_match('#_load\\.php$', $filepath))
        // The file ends with _load
    $filename = basename($filepath);
    $layout_name = substr($filename, strlen('template_'));
Josh Davis
This doesn't work. You need to use a look-behind negative assertion instead.
too much php
Yeah, I wasn't thinking about it the right way. Even though you want to capture something that is not followed by a substring, you have to look for something else that isn't preceded by it.
Josh Davis