0

I need to allow only letter, numbers, and underscores(_).

Anything else replace to space symbol ( _ ).

What's wrong with my regex pattern?

<?php
$val = 'dasd Wsd 23 /*~`';
$k = preg_replace('/[a-Z0-9_]+$/', '_', $val);
?>
Programmer.zip
  • 703
  • 3
  • 6
  • 14
user319854
  • 3,980
  • 14
  • 42
  • 45

2 Answers2

3

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);
0

[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.

Floern
  • 33,559
  • 24
  • 104
  • 119