user319854
user319854

Reputation: 4106

Replace one or more word characters with an underscore

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

Answers (2)

Floern
Floern

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

user142162
user142162

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

Related Questions