MyBB Community Forums

Full Version: need regex to clean a field name
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I really suck at regex and I need help to clean an entry for a field name in a database. That means letters, numbers and underscores only, no special chars or whitespace. All bad items should be replaced with an underscore

can someone post up the preg_replace() function that I would need to use?

Example

enter: item name
return: item_name

enter: item-name
return item_name

enter: item name*
return item_name_
Google would've probably worked just fine Toungue I just modified the second result I found, this should work (i think? my regex sucks too xD):
$field = blah&blah@#!$blah;
$new = preg_replace(“/[^a-zA-Z0-9\s]/”, “_”, $field);
$new = preg_replace("#[^\w]#", "_", $field);

^ within [] = not
\w = word (letters, digits and underscore)
(2011-10-14, 10:02 PM)patrick Wrote: [ -> ]$new = preg_replace("#[^\w]#", "_", $field);

^ within [] = not
\w = word (letters, digits and underscore)

does that replace the whole entry with an underscore or just the "non-word" parts?
that replaces each non word char with an underscore.

enter: item-name
return: item_name
enter: item - name
return: item___name
cool, thanks