...

View Full Version : Regex pattern problem



Nightchild
07-25-2007, 09:02 PM
I'm trying to write a filter that strips every character not suitable for a filename. So basically A-z 0-9 underscore, dash, period. I understand that period has special meaning but can you not escape it by using a backslash before it?



$string = "Testing O'Rielly 0123456789..~!@#$%^&*/\()_-=+";
$pattern = '/[^A-Za-z0-9 _-\.]/';

echo $string." : ".strlen($string)."<br />";
$string = preg_replace($pattern, '',$string);
echo $string." : ".strlen($string)."<br />";


This returns a blank string. If I remove the backslash + period I get all the other characters in the pattern.

What am I missing?

Thanks

ess
07-25-2007, 10:42 PM
Hi Nightchild

Try the following

// replace everything with '_'
$string = preg_replace('/[^a-z0-9_\.]/i', '_', $string);
// if file name ends with '_' remove it from the end of the file
$string = preg_replace('/_*$/i', '', $string);

I would use a function so you can reference it more than once, for example

function checkFileName( $string ) {
// replace everything with '_'
$string = preg_replace('/[^a-z0-9_\.]/i', '_', $string);
// if file name ends with '_' remove it from the end of the file
$string = preg_replace('/_*$/i', '', $string);
return $string;
}

Cheers,
Ess

Nightchild
07-26-2007, 02:39 AM
Thanks for the assist ESS...

As it turns out (took a break from this), the minus sign must have special meaning and I missed it in the docs. I escaped the minus sign and everything works fine.

One note: Using "A-z0-9" only will allow the ^, backslash, and underscore characters to get through unless I use "A-Za-z". I noticed this on the two servers I have access to (Linux SMESRVR and a Windows WAMP).



$string = "Testing O'Rielly 0123456789..~!@#$%^&*/\()_-=+";
$pattern = '/[^A-Za-z0-9 _\-\.]/';

echo $string." : ".strlen($string)."<br />";
$string = preg_replace($pattern, '',$string);
echo $string." : ".strlen($string)."<br />";


Yeah - my intent from the start was to make this a function in my functions.inc.php file. I just did it this way to try to figure things out.

Thanks



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum