8

I have a string in PHP and I want it to match the regex [A-Za-Z0-9]. How can I do this?

Malfist
  • 31,179
  • 61
  • 182
  • 269

3 Answers3

11

I am assuming you meant, a-z instead of a-Z, inside of your regex, but you can use preg_replace

$new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);

It takes as arguments the pattern ([a-zA-Z0-9]), replacement ("") and the subject ($string) and returns the new string ($new_string)

Anthony Forloney
  • 90,123
  • 14
  • 117
  • 115
4
$string = preg_replace('/[^a-zA-Z0-9]/', '', $string);
Anil Dewani
  • 217
  • 1
  • 2
  • 14
3

\W is a shortcut for [^a-Z0-9_]. May not be extremely helpful as it allows underscores too, but thought I'd let you know.

NikiC
  • 100,734
  • 37
  • 191
  • 225
Quasipickle
  • 4,383
  • 1
  • 31
  • 53