Reputation: 4106
I need to allow only letter, numbers, and underscores(_).
Anything else should be replaced a single underscore symbol ( _ ).
What's wrong with my regex pattern?
$val = 'dasd Wsd 23 /*~`';
$k = preg_replace('/[a-Z0-9_]+$/', '_', $val);
Upvotes: 0
Views: 3207
Reputation: 33904
[a-Z]
matches nothing.. You can use \W
to match non-word chars:
preg_replace('/\W+/', '_', $val)
Additionally the $
sign only matches at the end of a string.
Upvotes: 0
Reputation:
You needed to add the ^
which inverts the characters that are matched inside the character class.
$val = 'dasd Wsd 23 /*~`';
$k = preg_replace('/[^a-zA-Z0-9_]/', '_', $val);
Another way to do it is to have it match non "word" characters, which is anything that isn't a letter, number, or underscore.
$val = 'dasd Wsd 23 /*~`';
$k = preg_replace('/\W/', '_', $val);
Upvotes: 3