views:

80

answers:

3

I have a small chunk of coding I need to take from ereg to preg_match. Here is the code.

function be_file_list($d, $x) {
    foreach (array_diff(scandir($d), array('.', '..')) as $f) {
        if (is_file($d . '/' . $f) && (($x) ? ereg($x.'$',$f) : 1)) {
            $l[] = $f;
        }
    }

    return $l;
}

This code works as expected even if it doesn't look too pretty (source: http://www.php.net/manual/en/function.scandir.php)

but as ereg is deprecated, I would really like to make it preg_match, or something like that.

I have been messing with this all afternoon and the PC is about to go out the window. I would have thought that

preg_match("/"$x.'$',$f"/")

would have worked but no dice.

Any help would be great.

Cheers Ben

+1  A: 

You've got it all wrong... try

preg_match('/'.preg_quote($x, '/').'$/', $f)

You wrote:

preg_match("/"$x.'$',$f"/")

You need .s between the strings and vars, and you've got your trailing slash in the wrong place. It needs to be after the pattern, not after the subject.

Mark
A: 
preg_match("/" . $x . "$/", $f)

?

RC
A: 

Looks like glob is the thing you're looking for. Combining both directory reading and regular expressions

Col. Shrapnel
`glob` does **not** use regular expressions.
salathe
@salathe well sort of. enough for the OP's purpose
Col. Shrapnel