Question

I'm trying to write a function for converting bad file names to correct file names. I tryed to accomplish this with regex, which works well but throws an notice every time try to correct a name. This is my code:

private function clean_filename($filename) {
    $reserved = preg_quote('\/:*?"<>|', '/');
    $filename = preg_replace("/([\\x00-\\x20\\x7f-\\xff" .$reserved . "])/e", "_", $filename);
    return $filename;
}

The notice is:

Notice: Use of undefined constant _ - assumed '_' in C:\Documents and Settings\A dministrator\Desktop\script\script.php(89) : regexp code on line 1

Wht could be the problem? Thanks in advance!!

Was it helpful?

Solution

Using e forces an evaluation as a PHP expression. So you have to use:

$filename = preg_replace("/([\\x00-\\x20\\x7f-\\xff" .$reserved . "])/e",
    "'_'", $filename); //or "\"_\""; or '"_"' etc.

Even better would be dropping the e flag instead as you don't need it (your replacement expression is fixed; it's always an underscore character).

$filename = preg_replace("/([\\x00-\\x20\\x7f-\\xff" .$reserved . "])/",
    "_", $filename);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top