Thread: Using regex
View Single Post
Old 07-20-2009, 04:27 PM   #6 (permalink)
Salathe
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

Do you want to use a whitelist or a blacklist. The former would remove all characters except a specific set, e.g. allow only alphanumeric and hyphen characters. The latter, a blacklist, would remove only specific characters, e.g. !@#$%^&*().

It is also advised to use the PCRE functions (preg_replace) since the POSIX family of functions (ereg_*, split, etc.) is deprecated.

With regards to why ereg_replace("[[!-@],[:punct:]]","",$str) won't work, it's just how you've constructed the character set. There shouldn't be a set of square brackets around !-@. Note that that range includes the dash/hyphen character - so that will be removed.

Back to white- and blacklists, here are a few examples:
Only allow alphanumeric (case insensitive) and hyphen characters
PHP Code:
echo preg_replace('/[^a-z0-9-]/i'''$str); 
Only remove !@#$%^&*()+= characters
PHP Code:
echo preg_replace('/[!@#$%^&*()+=]/'''$str); 
Salathe is offline  
Reply With Quote