phpregexreplacesanitizationsnakecasing

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

Solution

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